For loops and arrays with sums

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

So it will look like this:

2.. 2
4.. 6 (4+2)
6.. 12 (6+4+2)
8.. 20 (8+6+4+2)
...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #include <iostream>
#include <string>
#include <Windows.h>

using namespace std;

int main() 
{

double sum[6] = {2, 4, 6, 8, 10, 12};
for(int i = 0; i < 6; i++)
	cout << sum[i]  << endl;
	


cin.get();
cin.get();
return 0;}


I only got here but I don't know how to get the running total printed.
Last edited on
closed account (j3Rz8vqX)
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;


Spoilers - possibilities:
http://pastie.org/8686084#7,10-12,14
http://pastie.org/8686092#12-22

Have fun
Last edited on
closed account (ivDwAqkS)
I think this is what you needed, I hope this helps you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace 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
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

 #include <iostream>
#include <string>
#include <Windows.h>

using namespace std;

int main() 
{
int a=0;
double sum[6] = {2, 4, 6, 8, 10, 12};
for(int i = 0; i < 6; i++){

        a=a+sum[i];
	cout << sum[i]  << endl;
	}
cout<<endl<<endl<<endl;
cout<<"The sum of the numbers in an array is : "<<a;
return 0;}


I think you need this
Topic archived. No new replies allowed.