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