Read the section of the tutorial Disch posted, about for loops.
Your problem involves for loops as well as an array. I would read the section on arrays as well, if you aren't already familiar with them:
http://cplusplus.com/doc/tutorial/arrays/
The loop structure is like this:
1 2
|
for (initialization; condition; increase)
{ ... statements to happen if condition is true .... }
|
Initialization is where you define and set a value for your increment variable. (i.e... int i = 0; )
Condition is where you set a conditional statement that, if determined to be true, will allow everything inside the body of the for loop to repeat until that conditional is false.
Increase is where you can increment or decrement your increment variable by one, for every iteration of the loop. (i.e... i++, ++i, i--, or --i) This will allow your for loop to be eventually false, avoiding an infinite loop in your program.
So you would want to have something like this for your for loop:
1 2 3 4 5
|
//the first for loop to set up each array element by using the above formula
for (int i=0; i<100;i++){
x[i] = i;
sum += x[i];
}
|
Really I don't see the point in creating a second, additional for loop. The one can handle both of your problems.
But for your sake, since some teachers want to see you practicing new concepts, you could use the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
using namespace std;
int main()
{
int x[100];
int sum = 0;
//the first for loop to set up each array element by using the above formula
for (int i=0; i<100;i++){
x[i] = i;
}
//the second for loop to compute the sum of all array elements and store it in sum
for (int i=0; i<100; i++)
sum += x[i];
cout << "Sum of all array elements is: " << sum << endl ;
system( "PAUSE");
return 0;
}
|