Java Reference
In-Depth Information
Only the variables total and counter need to be initialized before they're used. The variables
average and grade (for the calculated average and the user input, respectively) need not be
initialized, because their values will be replaced as they're calculated or input.
The pseudocode statement
Input, sum and count the quiz grades
requires repetition to successively input each grade. We do not know in advance how many
grades will be entered, so we'll use sentinel-controlled repetition. The user enters grades one
at a time. After entering the last grade, the user enters the sentinel value. The program tests
for the sentinel value after each grade is input and terminates the loop when the user enters
the sentinel value. The second refinement of the preceding pseudocode statement is then
Prompt the user to enter the first grade
Input the first grade (possibly the sentinel)
While the user has not yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Prompt the user to enter the next grade
Input the next grade (possibly the sentinel)
In pseudocode, we do not use braces around the statements that form the body of the
While structure. We simply indent the statements under the While to show that they be-
long to the While . Again, pseudocode is only an informal program development aid.
The pseudocode statement
Calculate and print the class average
can 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”
We're careful here to test for the possibility of division by zero —a logic error that, if unde-
tected, would cause the program to fail or produce invalid output. The complete second
refinement of the pseudocode for the class-average problem is shown in Fig. 4.9.
Error-Prevention Tip 4.4
When performing division ( / ) or remainder ( % ) calculations in which the right operand
could be zero, test for this and handle it (e.g., display an error message) rather than al-
lowing the error to occur .
1
Initialize total to zero
2
Initialize counter to zero
3
Fig. 4.9 | Class-average pseudocode algorithm with sentinel-controlled repetition. (Part 1 of 2.)
 
Search WWH ::




Custom Search