Back to DFS's Turing Page


Counted Repetition with the for 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 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 three triangles for which the user provides the dimensions.

The Pseudocode:

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

A for loop contains the statements that are to be repeated. 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 end for terminates.

When using a for loop, an integer counter 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 from one (1) to three (3) since this is easy for humans to understand.

Note that the value of the loop control variable is printed out each time the user is asked for the dimensions of a triangle.

% Calculating the areas of three (3) triangles
var b, h: int % Base & Height
var A: real   % Area
%---------------Introduction------------------
put "This program calculates and prints the areas of three triangles"
put "one after another after you enter their dimensions."
put "When asked to, type in a dimension and hit the ENTER key."
put ""
for counter : 1 .. 3
   %-------------------Inputting Data------------------
   put "Triangle #", counter, ":"
   put "What is the length of the triangle's base? "..
   get b
   put "What is the triangle's height? "..
   get h
   %---------------------Calculation------------------
   A := b * h / 2
   %-------------------Print the result---------------
   put "The area of a triangle with a base of ", b, " units and"
   put "a height of ", h, " units is ", A:0:1, " square units."
end for

© 1997-2004 DFStermole
HTMLified: 28 Dec 99
Last Modified 16 Feb 04