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 a user-specified number of triangles for which the user provides the dimensions.
The Pseudocode:
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 closing end for 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 starting with one (1) since this is easy for humans to understand. This way, we will be done after the HowMany-th time.
% Calculating the areas of a user-specified number of triangles var b, h, HowMany: int % Base, Height & # of triangles var A: real % Area %---------------Introduction------------------ put "This program calculates and prints the areas of triangles" put "one after another after you enter their dimensions." put "When asked to, type in a dimension and hit the ENTER key." %-------------------User Control------------------ put "How many areas do you wish to calculate? ".. get HowMany for counter : 1 .. HowMany %-------------------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