Skip to main content

Situation 1

If we know that there are 30 marks then a For loop should be used, and the program might be as follows:

 
Program UsingAForLoop1; 

Var 
Mark, Sum, LoopCount : Integer;
Average : Real;

Begin { UsingAForLoop1 }

Sum := 0;

For LoopCount := 1 TO 30 Do

Begin { For }

Write ('Enter a mark  ');
Readln (Mark);

Sum := Sum + Mark;

End; { For }

Average := Sum / 30;

Writeln;
Writeln ('The average is ', Average :6:2);

End. { UsingAForLoop1 }
 

Average is not calculated until the For loop has completed its execution, at which point the total sum will have accumulated.

The statements Sum := 0; and Sum := Sum + Mark; highlight an important feature in programming. When any kind of total is being accumulated, it should be set to zero before any loop is entered, so that it has a known starting value which can be incremented at the appropriate point in the program.

By the time the loop has exited, the value of Count will be 31.

Next: Situation 2