Skip to main content

Situation 3

If the number of marks to be entered is not known, one solution is to include a dummy mark after the final actual mark to indicate that the data has come to an end. The dummy mark should have a value (eg: a negative value) which cannot occur naturally in the real marks since it will be used to terminate the loop. The dummy mark is sometimes known as a sentinel. A suitable sentinel in this example might be 1 since it would not occur as a normal exam mark.

A For loop is not appropriate in this situation, but we could try a Repeat loop as follows:



    1. A running total is introduced to keep track of the number of marks entered in order that the average may be calculated.
    1. When the sentinel is entered it is added to the sum and the NoOfStudents is incremented by 1. Obviously this causes problems when the average is to be calculated since 1 was not an actual mark. For this reason a Repeat loop should be avoided in situations such as these as it can lead to bad programming techniques.

The only alternative left to the programmer is to use a While loop, which may be as follows:



  1. This program highlights an important feature of While loops. When a sequence of data is being entered in succession, the first value is read in before the start of the loop. This is necessary in order that we have something to test in the condition at the start of the loop. Each succeeding data value is read in within the loop once the previous value has been processed. This will normally be at the end of the loop. If a programmer omits the second Readln there is a very high risk that program execution will get stuck permanently within the loop since no new values will be read in and tested for the exit condition.
  1. It should be obvious at this stage that, in general, if the number of iterations of a loop as not known in advance, the While loop is more appropriate than the Repeat loop.

Next: Data Validation