Program Logic for Sentinel-Controlled Repetition vs. Counter-Controlled Repetition

Compare the program logic for sentinel-controlled repetition with that for counter-controlled repetition in Fig. 4.7. In counter-controlled repetition, each iteration of the while statement (lines 49–56 of Fig. 4.7) reads a value from the user, for the specified number of iterations. In sentinel-controlled repetition, the program reads the first value (lines 51–53 of Fig. 4.10) before reaching the while. This value determines whether the program’s flow of control should enter the body of the while. If the condition is false, the user entered the sentinel value, so the body does not execute (i.e., no grades were entered). If, on the other hand, the condition is true, the body begins execution, and the loop adds the grade value to the total (line 58) and increments gradeCounter (line 59). Then lines 62–63 in the loop’s body prompt for and input the next value from the user. Next, program control reaches the closing right brace (}) of the while’s body in line 64, so execution continues with the test of the while’s condition (line 56). The condition uses the most recent grade input by the user to determine whether the loop’s body should execute again. The value of variable grade is always input from the user immediately before the program tests the while condition. This allows the program to determine whether the value just input is the sentinel value before the program processes that value (i.e., adds it to the total and increments gradeCounter). If the sentinel value is input, the loop terminates, and the program does not add the value –1 to the total.

After the loop terminates, the if...else statement (lines 67–79) executes. The condition in line 67 determines whether any grades were entered. If none were, the else part (lines 78–79) of the if...else statement executes and displays the message "No grades were entered" and the member function returns control to the calling function.

Notice the block in the while loop in Fig. 4.10. Without the braces, the last three statements in the body of the loop would fall outside the loop, causing the computer to interpret this code incorrectly, as follows:

// loop until sentinel value read from user
while ( grade != -1 )
   total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
// prompt for input and read next grade from user
cout << "Enter grade or -1 to quit: ";
cin >> grade;

This would cause an infinite loop in the program if the user did not input –1 for the first grade (in line 53).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.243.106