168 Control Structures: Part 1 Chapter 4 Initialize (Hp web site)
Sunday, September 30th, 2007168 Control Structures: Part 1 Chapter 4 Initialize total to zero Initialize counter to zero 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) 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 Fig. 4.8Pseudocode algorithm that uses sentinel-controlled repetition to solve Fig. the class-average problem. Software Engineering Observation 4.5 Many algorithms can be divided logically into three phases: an initialization phase that initializes the program variables; a processing phase that inputs data values and adjusts program variables accordingly and a termination phase that calculates and displays the results. The pseudocode algorithm in Fig. 4.8 solves the more general class-averaging problem. This algorithm was developed after only two levels of refinement. Sometimes more levels are necessary. Software Engineering Observation 4.6 The programmer terminates the top-down, stepwise refinement process when the pseudocode algorithm is specified in sufficient detail for the programmer to be able to convert the pseudocode to a Java applet or application. Normally, implementing the Java applet or application is then straightforward. The Java application and a sample execution are shown in Fig. 4.9. Although each grade is an integer, the averaging calculation is likely to produce a number with a decimal point (i.e., a real number). The type intcannot represent real numbers (i.e., numbers with decimal points), so this program uses data type double to handle floating-point numbers. The program introduces a special operator called a cast operator to handle the type conversion we will need for the averaging calculation. These features are explained in detail in the discussion of the application. In this example, we see that control structures may be stacked on top of one another (in sequence) just as a child stacks building blocks. The while structure (lines 33 47) is followed by an if/elsestructure (lines 52 63) in sequence. Much of the code in this program is identical to the code in Fig. 4.7, so we concentrate in this example on the new features and issues. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01