In: Computer Science
Using the pseudocode found below, write only the actual (C++) code for this program. Include all libraries.
Specification:
Write a program that will repeatedly ask the user for quiz grades in the range from 0 to 20. Any negative value will act as a sentinel. When the sentinel is entered compute the average of the grades entered.
Design:
Constants
None
Variables
float grade
float total = 0
int count = 0
float average
-------
Inital Algorithm
Repeatedly ask user for grades until sentinel is entered
Compute average
Display average
Refined Algorithm
Repeatedly ask user for grades until sentinel is entered
Do
Display "Enter grade (0 – 20, or negative to quit) ---> "
Input grade
If grade >= 0 And grade <= 20 Then
total += grade
count ++
Else If grade > 20 Then
Display "Invalid grade. Try again." & EOL
End
While grade >= 0
Compute average
average = total / count
Display average
Set formatting for 2 decimal places
Display "The average of " & count & " grades was " & average & EOL
C++ Program:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float grade;
float total = 0;
int count = 0;
float average;
do {
cout << "Enter grade (0-20, or negative to quit) --> ";
cin >> grade;
if ((grade>=0) && (grade<=20)) {
total += grade;
count += 1;
}
else if (grade > 20) {
cout << "Invalid grade, Try again!!" << endl;
}
} while(grade>=0);
average = total / count;
cout << "\nThe average of " << count << " quiz marks is : " << fixed << setprecision(2) << average << endl;
return 0;
}
Output:
Thumbs Up Please !!!