Chapter 4 Control Structures: Part 1 161 Let (Web site)
Chapter 4 Control Structures: Part 1 161 Let us use pseudocode to list the actions to be executed and specify the order in which these actions should be executed. We use counter-controlled repetition to input the grades one at a time. This technique uses a variable called a counter to control the number of times a set of statements will execute. In this example, repetition terminates when the counter exceeds 10. In this section, we present a pseudocode algorithm (Fig. 4.6) and the corresponding program (Fig. 4.7) to solve this probem using counter-controlled repetition. In the next section, we show how pseudocode algorithms are developed. Counter-controlled repetition is often called definite repetition, because the number of repetitions is known before the loop begins executing. Note the references in the algorithm to a total and a counter. A total is a variable used to accumulate the sum of a series of values. A counter is a variable used to count in this case, to count the number of grades entered. Variables used to store totals should normally be initialized to zero before being used in a program; otherwise, the sum would include the previous value stored in the total s memory location. Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Fig. 4.6Pseudocode algorithm that uses counter-controlled repetition to solve Fig. the class-average problem. 1 // Fig. 4.7: Average1.java 2 // Class average program with counter-controlled repetition. 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 public class Average1 { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 int total, // sum of grades input by user 13 gradeCounter, // number of grades entered 14 gradeValue, // grade value 15 average; // average of all grades 16 String grade; // grade typed by user 17 Fig. 4.7Class-average program with counter-controlled repetition (part 1 of 3). Fig. 4. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01