I'm just learning about programming and computer science in general and I'm kind of stumped at the moment. I'm at a wall and its late and I'm getting kind of grumpy. I'm having some trouble with accumulating and the loop in this specific equation. Any help or pointers would be much appreciated.
Write a program that gets positive integers from the user and adds them together (accumulates their sum) until the user chooses to quit. It should recognize either Y or y as yes. N or any other character that the user enters other than Y or y causes the program to quit.
Do you want to add another number (Y/N): Y
Please enter the number to add: 3
The sum of the numbers so far is 3.
Do you want to add another number (Y/N): y
Please enter the number to add: 5
The sum of the numbers so far is 8
Do you want to add another number (Y/N): N
The sum of all of the numbers is 8.
This code does that exactly. Make sure you understand what's going on, I've commented it as well to make it easier. If you have any questions please ask.
#include <iostream>
usingnamespace std;
int main()
{
int number=0, sum=0;
char choice=NULL;
cout << "Obtaining the sum of numbers" << endl << endl; // Program description
system("pause");
cout << "\nPlease enter 'Y or y' to continue. Enter anything else to exit." << endl; // User input function
cout << "Enter a number? - ";
cin >> choice;
while(choice == 'Y' || choice == 'y') // If Y or y, then continue into sum function
{
cout << "\nEnter a number, (999 to Exit): ";
cin >> number;
if(number == 999) // Escape route for while loop
{
cout << "Exiting..." << endl << endl;
system("pause");
return (1);
}
cout << "Adding " << number << " to " << sum << endl << endl; // Sum function
sum = number + sum;
cout << "The total sum is: " << sum << endl << endl; // Sum output
}
if(choice != 'Y' || choice != 'y') // If statement for exiting if anything other than Y or y
{
cout << "\nExiting..." << endl;
system("pause");
return (1);
}
system("pause"); // This function is Windows based, so if using Unix, may not work.... just remove it if so....
return 0;
}