c++ decreasement in printing after y/n sessions

I'm not sure why, but every time after I type in yes, the program prints less numbers than requested after every session.

Like I want 5 numbers to be printed to later get the results: first time print 5 then results, second time print 4 then results, and it continues to decrease.

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
28
29
30
31
32
33
34
35
  #include <iostream>

using namespace std;

int main()

{
	int n, i;
    int num, sum=0;
	char ans;
    
	do {
		cout << "Enter the number of the desired amount numbers to calculate: ";
		cin >> n;
    	cout<< "Enter numbers for calculation: " << endl;

		do
		{
			cin >> num;
        	sum = sum + num;
        	i++;
		}
		while(i < n);
		
		cout<< "Answer: " << sum << endl;
		
		cout<< "Do you want to continue (Y/N)?" << endl;
		cout<< "You must type a 'Y' or an 'N' : " << endl;
    	cin >> ans;
    	cout<< endl;	
	}
	while((ans == 'Y') || (ans == 'y'));
	
	return 0;
}
Hello DigiLei,

First thing you need to do is initialize all of your variables. You are trying to use "i" at line 21 having no idea what value it has.

When you choose to continue and do another set you will need to reset your variables so you can start over instead of adding to them. I add this to the end of the outer do/while loop;

1
2
3
4
5
6
7
if (std::toupper(ans) == 'Y')  // <--- Requires header file <cctype>.
{
	sum = 0;
	i = 0;
	n = 0;
	num = 0;
}

This solved the problem because you are starting fresh. with your variables.

Hope this helps,

Andy

P.S. Watch your indenting.
Last edited on
Thank u
Topic archived. No new replies allowed.