Adding consecutive numbers using a loop

Jan 25, 2016 at 7:05pm
I'm having some trouble with this program:

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
#include <iostream>

using namespace std;

int main()

{

int n = 0;		//counter
int sum = 1;	//output
cout << "Please enter a number" << endl;
cin >> sum;
while ( n <= 6 )
{

    sum=n + sum;

    n++;
cout << "sum is" << sum << endl;
}

//cout << "sum is" << sum << endl;

return 0;
}


The final number should be 21 (1+2+3+4+5+6) if the number 1 is input. However, I'm getting 22. I'm not sure where I went wrong. Any help is appreciated, thanks!
Jan 25, 2016 at 7:11pm
If you input the number 1. Then the number 1 will be counted twice. it Would become -

(1+1+2+3+4+5+6)

Because sum would start at 1, then you would add 1 (because n would become 1).

It should really look like this -

(0+1+2+3+4+5+6) // notice the 0

So sum should be inputted as 0.
Last edited on Jan 25, 2016 at 7:11pm
Jan 25, 2016 at 7:16pm
when int sum = 0, I still get 22.
Jan 25, 2016 at 7:19pm
It doesnt matter what you initialize sum to, you can put int sum = 355; and it wouldnt change a thing, because in the next line of code you are going to overwrite it with your own user-inputted value. There you need to input 0.

Try this -

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

using namespace std;

int main()

{

int n = 0;		//counter
int sum = 0;	//output

while ( n <= 6 )
{

    sum=n + sum;

    n++;
cout << "sum is" << sum << endl;
}

//cout << "sum is" << sum << endl;

return 0;
}
Jan 25, 2016 at 7:24pm
When I input 0, I get 21 as expected:
1
2
3
4
5
6
7
8
9
Please enter a number
0
sum is0
sum is1
sum is3
sum is6
sum is10
sum is15
sum is21


edit: Your post seems to imply you changed line 10. As TarikNeaj pointed out, the value you initialize sum to makes no difference since you overwrite it with your cin statement.
Last edited on Jan 25, 2016 at 7:33pm
Topic archived. No new replies allowed.