Trouble with another program

I'm supposed to make a program that uses a vector with 20 values, and the first 3 are predefined num[20]={1,2,3}. The program is then supposed to then fill in the remaining 17 values by ending the sum of the previous ones so the next value would be 6, then 12. I am able to get 6 but then my code doesn't work after that. Any help is appreciated!

#include <iostream>
using namespace std;
int main ()
{


int num[20]={1,2,3};


for (int i=3; i<=20; i=i++)
{
int sum=0;
for (int x=i-1;x>=0;x--)
{
sum=sum+num[x];
}
num[i]=sum;
for (i=0; i<=20; i++)
{
cout<<num[i]<<endl;
}
}


system("pause");
return 0;
}
are you supposed to use a vector or an array? at the moment you are using an array.

For your for loop, here is what you will want to do:
1
2
3
4
5
6
7
8
9
10
11
12
13
for (int i=3; i<=20; i++)
{
int sum=0;
for (int x=i-3;x<i;x++)
{
sum=sum+num[x];
}
num[i]=sum;
for (i=0; i<=20; i++)
{
cout<<num[i]<<endl;
}
}


Made this code in a rush, dont have time to proofread this. Hopefully the other forum posters and edit this, but you have the skeleton of what you should do now.
Sorry I meant array. And the code that you gave me is giving me the same output i had with my original code which was
1
2
3
6
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2686792
Press any key to continue . . .
Making it somewhat simplier:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;
int main ()
{


int num[20]={1,2,3};

int i;
for (i=3; i<20; i++) // i==20 -> out of bounds!
{
int sum=0;
for (int x=0;x<i;x++) // No need to go backward
{
sum+=num[x];
}
num[i]=sum;
}
// this loop must be outside
for (i=0; i<20; i++) //  i==20 -> out of bounds!
{
cout<<num[i]<<endl;
}


system("pause");
return 0;
}
Last edited on
Topic archived. No new replies allowed.