#include <iostream>
usingnamespace 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!
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.
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.