Crystaltech web hosting - Chapter 4 Control Structures: Part 1 167 may
Chapter 4 Control Structures: Part 1 167 may be refined as follows: Initialize total to zero Initialize counter to zero Notice that only the variables total and counter are initialized before they are used; the variables average and grade (for the calculated average and the user input, respectively) need not be initialized, because their values are replaced as they are calculated or input. The pseudocode statement Input, sum up and count the quiz grades requires a repetition structure (i.e., a loop) that successively inputs each grade. We do not know how many grades the user will input, so the program will use sentinel-controlled repetition. The user at the keyboard inputs legitimate grades one at a time. After inputting the last legitimate grade, the user types the sentinel value. The program tests for the sentinel value after each grade is input and terminates the loop when the user inputs the sentinel value. The second refinement of the preceding pseudocode statement is then Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) Notice that in pseudocode, we do not use braces around the pseudocode that forms the body of the while structure. We simply indent the pseudocode under the while, to show that it belongs to the while. Again, pseudocode is only an informal program development aid. The pseudocode statement Calculate and print the class average may be refined as follows: If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print No grades were entered Notice that we are testing for the possibility of division by zero a logic error that, if undetected, would cause the program to produce invalid output. The complete second refinement of the pseudocode algorithm for the class-average problem is shown in Fig. 4.8. Testing and Debugging Tip 4.1 When performing division by an expression whose value could be zero, explicitly test for this case and handle it appropriately in your program (such as by printing an error message) rather than allowing the division by zero to occur. Good Programming Practice 4.9 Include completely blank lines in pseudocode programs to make the pseudocode more readable. The blank lines separate pseudocode control structures, as well as the phases of the programs. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01