Hi, here is a piece of code i read from the book.
The original question is : Develop a class averaging program that will process an arbitrary number of grades each time the program is run.
Since there is no indication given of how many grades are to be entered, so they introduced sentinel-control-structure.
Code:
// average grade
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int total, // sum of grades
grade, // one grade
gradeCounter; // number of grades entered
float average; // class average
//initialization
total = 0;
gradeCounter = 0;
// PROCESSING
cout << "Enter grade, -1 to end the program: ";
cin >> grade;
while ( grade != -1 ) {
total = totoal + grade;
gradeCounter = gradeCounter +1;
cout << "Enter grade, -1 to end the program: ";
cin >> grade;
}
// termination
if ( gradeCounter !=0 ){
average = static_cast< float > ( total ) / gradeCounter;
cout << "Class average is " << setprecision( 2 )
<< setiosflags ( ios::fixed | ios::showpoint )
<< average << endl;
}
else
cout << "NJ grade were entered" << endl;
return 0; // program ended successfully
}
the following is code for counter-control-structure
Code:
// average grade
#include <iostream>
using namespace std;
int main()
{
int total, // sum of grades
gradeCounter, // number of grades entered
grade, // individual grade
average; // average of grades in this class
// now we should first re-set some of the values
total = 0; // make sure total always starts with zero
gradeCounter = 1; // starting from 1, ends at 10
// enter all ten grades
while ( gradeCounter <=10 ) {
cout << "Enter grade: ";
cin >> grade;
total = total + grade;
gradeCounter = gradeCounter +1;
}
cin.get();
// get all ten and finally calcaulate this
average = total / 10;
cout << "Class average is " << average << endl;
cin.get();
return 0;
}
What I don't understand is to compare to counter-control-strcuture, which you know the number of grades will be entered, the book sets the initialization a bit different.
(1) For sentinel, which is the first prorgram, the gradeCounter is set to zero, why? In counter example, the gradeCounter starts from +1. I just don't get the reason, maybe i am too dumb...?