So I'm slowly learning C++ and while I understand most of it, I have hit a wall in the most recent code I've been working on.
Basically I need to get the computer to execute a program that asks the user how many integer values they want to get the sum for.
Once the user enters their desired numbers, the computer will add them all up and display the sum to the user.
It will then ask the user if they want to go again.
Simple. Or it should be. I think...
Anyways! I have most of that down but when I run it and try it for myself, I run into the issue of the computer taking the previous sum and adding it to the new sum. I need help with keeping the sums separate and individual while having the computer run a loop of a new group of integers and their sum.
#include <iostream>
usingnamespace std;
int main()
{
int n;
int x;
int ii;
int sum = 0;
char goAgain = 'y';
do {
cout << "How many integer values would you like to sum? ";
cin >> n;
cout << endl;
if (n <= 0) {
break;
}
else {
for (x = 1; x <= n; x++) {
cout << "Enter an integer value: ";
cin >> ii;
sum += ii;
}
cout << endl;
cout << "The sum is " << sum << endl;
cout << endl;
}
cout << "Would you like to go again (y/n)? ";
cin >> goAgain;
cout << endl;
} while (goAgain == 'y');
if (goAgain != 'y') {
cout << "Goodbye!" << endl;
}
cout << endl;
return 0;
}
Just to be able to have this closed - I have found the issue and resolved it. Incase someone comes across this forum, here's the source code of the resolved issue:
int main()
{
int n; // determines how many times to loop
int x; // variable to control number of "for" loops against number of needed integers 'n'
int ii; // integers that will be summed during loop
int sum; // total of all integers
char goAgain = 'y';
do {
cout << "How many integer values would you like to sum? ";
cin >> n;
cout << endl;
sum = 0;
for (x = 1; x <= n; x++) {
cout << "Enter an integer value: ";
cin >> ii;
sum += ii;
}
cout << endl;
cout << "The sum is " << sum << endl;
cout << endl;
cout << "Would you like to go again (y/n)? ";
cin >> goAgain;
cout << endl;
} while (goAgain == 'y');
if (goAgain != 'y') {
cout << "Goodbye!" << endl;
}
cout << endl;
return 0;
}
Pretty much I had sum = 0 at the top with the other variables but really, I needed to have sum = 0 within the loop code itself. :)