#include <iostream>
usingnamespace std;
int main()
{
cout<<"This program computes the average of ";
cout<<"a list of (nonnegative) exam scores."<<endl;
double sum;
int numberOfStudents;
double next;
char answer;
do
{
cout<<"Enter all the scores to be averaged."<<endl;
cout<<"Enter a negative number after ";
cout<<"you have entered all the scores."<<endl;
sum = 0;
numberOfStudents = 0;
cin>>next;
while (next >= 0)
{
sum = sum + next;
numberOfStudents++;
cin>>next;
}
if (numberOfStudents > 0)
cout<<"The average is "<<(sum / numberOfStudents)<<endl;
else
cout<<"No scores to average."<<endl;
cout<<"Want to average another exam?"<<endl;
cout<<"Enter y for Yes or n for no."<<endl;
cin>>answer;
}
while (answer=='y'|| answer=='Y');
system ("pause");
return 0;
}
It is a simple C++ Program to generate average of non negative numbers that are inputted by the user.
It generates the average of only non negative numbers because it uses a condition here.
1 2 3 4 5 6
while (next >= 0)
{
sum = sum + next;
numberOfStudents++;
cin>>next;
}
This block of code checks for terminating condition which is a negative number.As soon as user inputs a negative number then "next" becomes < 0 and hence while loop terminates which makes that negative number not to be included in "sum".
The do-while loop will only be terminated when user enters (y or Y) in this part of code.
1 2 3
cout<<"Want to average another exam?"<<endl;
cout<<"Enter y for Yes or n for no."<<endl;
cin>>answer;
if user enter any character in between the program, it means assigning an integer variable to a character valueand thus the programs runs out for infinite.