Formulating Algorithms: Counter-Controlled Repetition

A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.

The class average is equal to the sum of the grades divided by the number of students.

The algorithm for solving this problem on a computer must input each grade, keep track of the total of all grades input, perform the averaging calculation and print the result.

Use counter-controlled repetition to input the grades one at a time.

A variable called a counter (or control variable) controls the number of times a set of statements will execute.

Counter-controlled repetition is often called definite repetition, because the number of repetitions is known before the loop begins executing.

A total is a variable used to accumulate the sum of several values.

A counter is a variable used to count.

Variables used to store totals are normally initialized to zero before being used in a program.

Click here to see the codes.

Variables declared in a method body are local variables and can be used only from the line of their declaration to the closing right brace of the method declaration.

A local variable’s declaration must appear before the variable is used in that method.

A local variable cannot be accessed outside the method in which it’s declared.

The program’s output indicates that the sum of the grade values in the sample execution is 846, which, when divided by 10, should yield the floating-point number 84.6.

The result of the calculation total / 10 (line 61 of Fig. 4.6) is the integer 84, because total and 10 are both integers.

Dividing two integers results in integer division—any fractional part of the calculation is lost (i.e., truncated).

Example:  7 / 4 = 1, not 2, not 1.75.