Getting the sum of values in an array?

I'm using C++.

What I have so far:

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

using namespace std;

int main()
{
	int a, sum;

	int arrayname[] = {1, 2, 3, 4, 5};

	for (a=0; a<5; a++)
	{
		sum = 0;

		sum+=arrayname[a];
	}

	cout << sum << endl;

	return 0;
}


When "sum" is shown onscreen, it has a value of 5 whereas I think it *should* have a value of 15 because 1+2+3+4+5 = 15. I'm just confused as to why it's not equaling 15. I have the sum within the loop.
Last edited on
intialize sum outside the for loop each time u loop the sum value is restarted to zero the right code should be like that
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
#include <iostream>

using namespace std;

int main()
{
	int a, sum = 0 ;

       /* or use this
            int a,sum;
            sum = 0;
        */

 
	int arrayname[] = {1, 2, 3, 4, 5};

	for (a=0; a<5; a++)
	{
		

		sum+=arrayname[a];
	}

	cout << sum << endl;

	return 0;
}


and this question should go to beginner forum
OK. I'll keep that in mind next time. Is there anyone that can moves threads?

I used this code, by the way, and it worked. I for some reason eventually resolve my issues, but only after posting. >.>

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

using namespace std;

int main()
{
        int sum=0;

        int arrayname[] = {1, 2, 3, 4, 5};

        for (int a=0; a<5; a++)
        {
			sum+=arrayname[a];
        }
        
        cout << sum << endl;
        
        return 0;
}
Last edited on
Topic archived. No new replies allowed.