In: Computer Science
Write a program that uses a while loop with a priming read to ask the user to input a set positive integers. As long as the user enters a number greater than -1, the program should accumulate the total, keep track of the number of numbers being entered and then calculate the average of the set of numbers after the user enters a -1. This is a sentinel controlled-loop.
Here is what a sample run should look like:
Enter the first number (-1 to
quit):<SPC>20<ENTER>
Enter another number (-1 to quit):<SPC>92<ENTER>
Enter another number (-1 to quit):<SPC>34<ENTER>
Enter another number (-1 to quit):<SPC>76<ENTER>
Enter another number (-1 to quit):<SPC>97<ENTER>
Enter another number (-1 to quit):<SPC>57<ENTER>
Enter another number (-1 to quit):<SPC>-1<ENTER>
The total is 376, the average is 53.71<LINERETURN>
Solution
Code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number,count=0;
float total=0.0,average;
cout<<"Enter the first number (-1 to quit): ";
cin>>number;
while(number!=-1)
{
total=total+number;
cout<<"Enter the another number (-1 to quit): ";
cin>>number;
count++;
}
average=total/(count+1);
cout<<"The total is "<<total<<", the average is
"<<fixed<<setprecision(2)<<average;
return 0;
}
Screenshot
Output
--
programming language not mentioned
so i have done using c++
if you have any doubt, please mention it
love to help
all the best