Back to DFS's Pascal Page


User-Controlled Repetition with the For-To-Do Loop

Computers are excellent at doing the same operation over and over again. If it is already known how many times an action is to be done, the For-To-Do loop is usually the preferred programming structure. It is also used if the number of repetitions is specified by the user or can be calculated. We will use a modification of the area-of-a-triangle program to illustrate this. The problem, pseudocode and flowchart are as follows:

The Problem: Write a program to calculate the areas of a user-specified number of triangles for which the user provides the dimensions.

The Pseudocode:

  1. Simple introduction and instructions;
  2. Do the main job repeatedly
       a) Find out the dimensions;
       b) Calculate the area;
       c) Print out the results.

A For-To-Do loop contains the statements that are to be repeated. These statements are enclosed by curly BEGIN/END, forming what is called a compound statement. Indentation is used to help the programmer visualize the structure of the loop. A comment is frequently placed at the end of the loop so you know which loop the closing curly terminates.

When using a For-To-Do loop, a variable is used to keep track of which iteration of the loop is being done. This is known as the "loop control variable" and is given the name counter in this program, since we are having the computer count the iterations. For this problem, we will use the Natural numbers starting with one (1) since this is easy for humans to understand. This way, we will be done after the HowMany-th time.

program TriangleHowMany (input, output);
   var
      b, h: integer; {Base & Height}
      A: real; {Area}
      HowMany, Counter: integer; {Loop variables}
   begin
      {---------------Introduction------------------}
      writeln('This program calculates and prints the areas of triangles');
      writeln('one after another after you enter their dimensions.');
      writeln('When asked to, type in a dimension and hit the ENTER key.');
      {-------------------User Control------------------}
      write('How many areas do you wish to calculate? ');
      readln(HowMany);
      writeln;
      For Counter := 1 To HowMany Do
         begin
            {-------------------Inputting Data------------------}
            writeln('Triangle #', counter:0, ':');
            write('What is the length of the triangle''s base? ');
            readln(b);
            write('What is the triangle''s height? ');
            readln(h);
            {-------------------Calculation------------------}
            A := b * h / 2;
            {-------------------Printing Results------------------}
            writeln('The area of a triangle with a base of ', b:0, ' units and');
            writeln('a height of ', h:0, ' units is ', A:0:1, ' square units.');
            writeln
         end {End of For loop}
   end.

© 1998-99 DFStermole
HTMLified: 28 Dec 99
Last Modified: 15 Feb 04