Counter-controlled repetition

Counter-controlled repetition requires

  1. The name of a control variable (or loop counter)

  2. The initial value of the control variable

  3. A condition that tests for the final value of the control variable (i.e., whether looping should continue)

  4. An increment (or decrement) by which the control variable is modified each time through the loop

Example:  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.

 

#include <stdio.h>

int main()
{
int counter, grade, total, average;

/* initialization phase */
total = 0;
counter = 1;

/* processing phase */
while ( counter <= 10 ) {
printf( "Enter grade: " );
scanf( "%d", &grade );
total = total + grade;
counter = counter + 1;
}

/* termination phase */
average = total / 10;
printf( "Class average is %d\n", average );

return 0; /* indicate program ended successfully */
}