Filename: numbers.cpp Write a program that will allow the user to enter a set of
ID: 3902600 • Letter: F
Question
Filename: numbers.cpp
Write a program that will allow the user to enter a set of integers (as many as they want), then prints out a summary of information, as follows:
Prompt the user continually to enter a number using a loop, until the value 0 is entered, which will be the signal to stop entering values. (This is sometimes known as a "sentinel" value).
Once the sentinel value has been entered, print out the following information:
The number of positive values that were input
The number of negative values that were input
The sum of the input values
The average (to two decimal places) of the input values
Your output must match mine exactly. See the sample runs below
Sample Runs
(user input is underlined, to distinguish it from output)
Sample Run 1
Sample Run 2
Sample Run 3
Explanation / Answer
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// declaring variables
int positive = 0, negative = 0, sum = 0, count = 0, number;
double average = 0;
// taking first input
cout << "Enter a Number (0 to stop): ";
cin >> number;
while(number != 0)
{
// updating number of positive and negative numbers
if(number > 0)
positive++;
else
negative++;
sum+= number;
// taking input
cout << "Enter a Number (0 to stop): ";
cin >> number;
// incrementing count by 1
count++;
}
// setting average
if(count > 0)
average = sum/(count*1.0);
// printing output
cout << endl << "# of positives = " << positive;
cout << endl << "# of negatives = " << negative;
cout << endl << "Sum = "<< sum;
cout << endl << fixed << setprecision(2) << "Average = " << average;
}
/*SAMPLE OUTPUTS
Enter a Number (0 to stop): 12
Enter a Number (0 to stop): 4
Enter a Number (0 to stop): -1
Enter a Number (0 to stop): -5
Enter a Number (0 to stop): 18
Enter a Number (0 to stop): 0
# of positives = 3
# of negatives = 2
Sum = 28
Average = 5.60
Enter a Number (0 to stop): 4
Enter a Number (0 to stop): 8
Enter a Number (0 to stop): 24
Enter a Number (0 to stop): 94
Enter a Number (0 to stop): -1
Enter a Number (0 to stop): 43
Enter a Number (0 to stop): 13
Enter a Number (0 to stop): 0
# of positives = 6
# of negatives = 1
Sum = 185
Average = 26.43
Enter a Number (0 to stop): 0
# of positives = 0
# of negatives = 0
Sum = 0
Average = 0.00
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.