blog
blog copied to clipboard
C++ Sentinels
Concept: A sentinel is a special value that marks the end of a list of values.
A sentinel is a special value that cannot be mistaken as a member of the list and signals that there are no more values to be entered. When the user enters the sentinel, the loop terminates.
#include <iostream>
using namespace std;
int main() {
const int SENTINEL_VAL = -1;
float quiz_grade;
float total_grade = 0;
int num_quizzes = 0;
cout << "Type a quiz grade (type -1 if you don't have any more quiz grades): ";
cin >> quiz_grade;
while (quiz_grade != SENTINEL_VAL) {
num_quizzes++;
total_grade += quiz_grade;
// Update quiz_grade:
cout << "Type a quiz grade (type -1 if you don't have any more quiz grades): ";
cin >> quiz_grade;
// total_grade += quiz_grade; // SENTINEL_VAL will be included in the running total_grade
}
cout << "Total grade: " << total_grade << endl;
cout << "Average grade: " << total_grade / num_quizzes << endl;
return 0;
}
The value -1
was chosen for the sentinel in the program because it is not possible for a team to score negative points.