Skip to main content

Situation 2

If we don't know the number of marks until the program is executed it is once again possible to use a For loop:

 
Program UsingAForLoop2;

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

Begin { UsingAForLoop2 } 

Sum := 0; 

Write ('Enter the number of students ');
Readln (NoOfStudents);

For LoopCount := 1 TO NoOfStudents Do
Begin { For }

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

Sum := Sum + Mark;

End; { For }

Average := Sum / NoOfStudents;

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

End. { UsingAForLoop2 }
 

The number of times that the For loop will be executed depends on the value entered for the number of students when the program is run.

The number of students entered is used in the calculation of the average.

Next: Situation 3