user3424696
user3424696

Reputation: 27

add results of a for loop after each iteration

I‘m having trouble with my for loop. I have a basic 2 times table that goes up from 1 to 10. (see below). I'm trying to add the result so that after every loop, allResult displays the values of all results added. it needs to show all results added after every loop. and I don't know how to go about it. A better description is the desired outcome commented in the code.

my Code...

int main(){

int allResult;

for( int i = 1; i < 11; i++)
{

    int result = 2*i;

    cout << 2 << " times " << i << " = " <<  result << endl;

    // I want allResult to store results added. so after first loop, result = 2 so allResult = 2
    // after second loop, result = 4. so allResult should be 6. (results from 1 and 2 added)
    // after third loop, result = 6 so allResult should be 12. (results from 1, 2 and 3 added)
    // I'm trying to apply this to something else, that uses random numbers, so i cant just * result by 2.


}
system("pause");
}

Upvotes: 1

Views: 2276

Answers (3)

Code_Jamer
Code_Jamer

Reputation: 913

int main()
{

int allResult=0;

 for( int i = 1; i < 11; i++)
  {

      int result = 2*i;

      allResult=allResult+result; 
/*Initially allResult is 0. After each loop iteration it adds to its previous 
value. For instance in the first loop it was allResult=0+2, 
which made allResult equal to 2. In the next loop allResult=2+4=6. 
Third Loop: allResult=6+6=12. Fourth loop:allResult 12+8=20 and so on..*/

cout << 2 << " times " << i << " = " <<  result << endl;
  }

      system("pause");
}

Upvotes: 1

Alaeddine
Alaeddine

Reputation: 1677

int allResult = 0;
for( int i = 1; i < 11; i++)
{
     allResult += 2*i;  
    cout << 2 << " times " << i << " = " <<  2*i << endl;

}

Upvotes: 3

Eric Fortin
Eric Fortin

Reputation: 7603

int allResult = 0;
for( int i = 1; i < 11; i++)
{
    int result = 2*i;

    cout << "2 times " << i << " = " <<  result << endl;
    allResult += result;
    cout << "allResult: " << allResult << endl;
}

Upvotes: 2

Related Questions