Write a program in C++ that asks the user to enter some positive numbers until 0
ID: 3654854 • Letter: W
Question
Write a program in C++ that asks the user to enter some positive numbers until 0 is entered. The program then reports the total of all even numbers entered. The users can enter as many numbers as they want. When negative numbers are entered, present a message to the user for the error but continue the program.
Following is the code I have gotten to be the closest. What am I doing wrong?
#include <iostream>
using namespace std;
int main()
{
int row = 1, //row counter
number, //holds number entered
total = 0; //sum of numbers
//Instructions
cout << "Please enter any positve, non-zero number. ";
cout << "Do this as many times you would like. ";
cout << "When done, enter a "0", to receive the total of all even numbers entered. ";
cout << " Please enter your number choice " << row << ": ";
cin >> number;
// Total will only add even numbers
if (number%2 == 0)
{
total += number;
}
while ( number != 0)
{
row ++;
total += number;
cout << "Please enter your number choice " << row << ": ";
cin >> number;
if ( number == 0)
{
cout << " The total sum of the even numbers entered is " << total << endl;
if ( number < 1)
{
cout << "Please enter a number 1 or greater: ";
cin >> number;
}
}
}
cout << " The total sum of the even numbers entered is " << total << endl;
return 0;
}
--sorry if it doesn't come out formatted..again--
Explanation / Answer
//C++ code
#include <iostream>
using namespace std;
int main()
{
int row = 1; //row counter number,
//holds number entered
int number;
int total = 0;
//sum of numbers
//Instructions
cout << "Please enter any positve, non-zero number. ";
cout << "Do this as many times you would like. ";
cout << "When done, enter a "0", to receive the total of all even numbers entered. ";
cout << " Please enter your number choice " << row << ": ";
cin >> number; // input number
while (true)
{
if (number%2 == 0 && number != 0)
{
total += number;
}
else if ( number == 0)
{
cout << " The total sum of the even numbers entered is " << total << endl;
break;
}
row ++;
//count number
// Display proper msg
if ( number < 0)
cout << "Please enter a number 1 or greater: ";
else
cout << "Please enter your number choice " << row << ": ";
cin >> number; // input number
}
return 0;
}
/*
output:
Please enter any positve, non-zero number.
Do this as many times you would like.
When done, enter a "0", to receive the total of all even numbers entered.
Please enter your number choice 1: 3
Please enter your number choice 2: 4
Please enter your number choice 3: 5
Please enter your number choice 4: 6
Please enter your number choice 5: 0
The total sum of the even numbers entered is 10
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.