Hey guys I'm learning for loop and in my book I have an exercise to display an array of integers. That all works but I also need to print the running total of the integers next to it
Curly braces can be used to group code under a single scope.
Example:
1 2 3 4 5 6 7
for (int i = 0; i < 10; i++){
//The following comments are encapsulated in this for-loop
//comment here #1
//comment here #2
//..
//comment here #999
}
Implement an accumulator in your main and embed it in your for-loop; possibly a variable of type double, initialized as 0, used in your for-loop.
It should do what it's name implies; accumulate.
Example:
1 2 3
//Within the scope of a for loop:
total += sum[i];//total should be declared before this for-loop
cout<<total<<endl;
#include <iostream>
usingnamespace std;
int main(){
int sum=0; // we need a temp to start doing the sum
int varr[6] = {2, 4, 6, 8, 10, 12}; /*I changed the name of the array
(you don't have to, but If you do not change it
then change the name of the int sum)*/
for(int i = 0; i < 6; i++){
sum+=varr[i]; // it sums 0 + first value of the array witch is 2
cout << i+1 << ".- " << sum << endl;// it prints the sum
}//the loop returns
cout << "the total of the sum is " << sum << endl;/* gives you the last total of the sum
when the loop is finished*/
return 0;
}
output:
1.- 2
2.- 6
3.- 12
4.- 20
5.- 30
6.- 42
the total of the sum is 42