Back to DFS's C 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. These statements are enclosed by curly brackets, 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 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 from one (1) to three (3) since this is easy for humans to understand.

#include <stdio.h> /* standard I/O header file */
void main()
{
   int b, h; /* base, height */
   float A; /* Area */
   int counter; /* Loop control variable */
   /* -------------------Introduction------------------ */
   printf("This program calculates and prints the areas of three triangle\n");
   printf("one after another after you enter their dimensions.\n");
   printf("When asked to, type in a dimension and hit the ENTER key.\n");
   printf("\n");
   for(counter = 1; counter <= 3; counter++)
   {
      {-------------------Inputting Data------------------}
      printf("Triangle #%d:\n", counter);
      printf("What is the length of the triangle's base? ");
      scanf("%d", &b);
      printf("What is the triangle's height? ");
      scanf("%d", &h);
      /* -------------------Calculation------------------ */
      A = b * h / 2.0;
      /* -------------------Printing Results------------------ */
      printf("\n");
      printf("The area of a triangle with a base of %d units and\n", b);
      printf("a height of %d units is %.1f square units.\n", h, A);
   } /* End of for loop */
}

© DFStermole: 3 Oct 98
HTMLified: 3 Oct 98