The example of Figs. 4.6–4.7 demonstrates a nested if…else statement that determines a student’s letter grade based on the student’s average in a course.
Class Student
Class Student (Fig. 4.6) stores a student’s name and average and provides member functions for manipulating these values. The class contains:
Data member name of type string (line 65) to store a Student’s name.
Data member average of type int (line 66) to store a Student’s average in a course.
A constructor (lines 8–13) that initializes the name and average.
Member functions setName and getName (lines 16–23) to set and get the Student’s name.
Member functions setAverage and getAverage (lines 26–39) to set and get the Student’s average—in Section 5.11, you’ll learn how to express lines 29–30 more concisely with logical operators that can test multiple conditions.
Member function getLetterGrade (lines 42–63), which uses nestedif…elsestatements to determine the Student’s letter grade based on the Student’s average.
After the constructor initializes name in the member-initializer list, the constructor calls member function setAverage, which uses nestedifstatements (lines 29–33) to validate the value used to set the average. These statements ensure that the value is greater than 0and less than or equal to 100; otherwise, average’s value is left unchanged. Each if statement contains a simple condition—i.e., one that makes only a single test. In Section 5.11, you’ll see how to use logical operators to write compound conditions that conveniently combine several simple conditions. If the condition in line 29 is true, only then will the condition in line 30 be tested, and only if the conditions in both lines 29 and 30 are true will the statement in line 31 execute.
Class StudentTest
To demonstrate the nested if…else statements in class Student’s getLetterGrade member function, the main function (Fig. 4.7) creates two Student objects (lines 8–9). Next, lines 11–16 display each Student’s name, average and letter grade by calling the objects’ getName, getAverage and getLetterGrade member functions, respectively.