Lesson 3. Iteration Construct.

 

In Pascal programming, there are 3 proper ways with which to create a loop by using any one of the following :-

 

A loop is needed when one instruction or a group of instruction need to be repeated. Normally there will be a stopping condition in which the looping action will terminate itself.

 

FOR..DO

 

The FOR..DO loop is based on a counter. Here is the syntax and an example.

 

FOR cnt.var := start [TO/DOWNTO] stop DO

BEGIN

loop statement body;

END;

 

The pseudocode:

DO FOR var IN RANGE OF start TO stop

loop statement body

ENDDO

 

Example 4-1

program ForLoopTest;

uses CRT;

var

I : integer;

begin { main program }

ClrScr;

WriteLn('Values generated by the FOR..DO loop ');

for I := 1 to 10 do

Write( I : 4 );

WriteLn;

WriteLn('Reverse values ...');

for I := 10 downto 1 do

Write( I : 4 );

WriteLn;

ReadLn;

end. { main program }

 

In this example, a forward loop and a reverse loop is illustrated.

 

Things to note :

  1. The increment or decrement value is always 1.
  2. FOR..DO loop are used when the number of repetition is "fixed" or is known in advance.
  3. The variable used in the loop, the starting and stopping values must all be of ordinal types.

 

Here's a code segment using the character type as the counter variable.

 

for Ch := 'A' to 'Z' do

Write( Ch:2 );

 

The variable CH is declared as CHAR. This code segment displays the alphabets from 'A' to 'Z'.

Here is the complete program...

 

program ForDoLoop2;

uses CRT;

var

Ch : char;

begin

ClrScr;

for Ch := 'A' to 'Z' do

Write( Ch );

WriteLn;

for Ch := 'z' downto 'a' do

Write( Ch );

WriteLn;

ReadLn;

end.

 

 

WHILE..DO

 

The WHILE..DO loop is a conditional loop.

 

The syntax of a WHILE..DO loop looks like this:

 

WHILE condition-list DO

BEGIN

loop statement body;

END;

 

The pseudocode:

 

DO WHILE condition-list

loop statement body

ENDDO

 

Features:

 

General Example

WHILE there's homework DO

homework;

 

or

 

WHILE tired DO

rest;

 

 

 

 

 

An example using a WHILE..DO loop to accept and accumulate values:

 

program TestWhileDo;

uses CRT;

var

I : integer;

Sum : integer;

begin { main program }

ClrScr;

WriteLn( 'Type in some numbers.Press <ENTER> after’, ‘every number.');

WriteLn( 'Type 0 to stop the programand display the’, ‘results.')

I := 1; Sum := 0;

while I <> 0 do

begin

Write('Number ? ');

ReadLn( I );

Sum := Sum + I;

end;

WriteLn('The sum of all the numbersis ', Sum );

ReadLn;

end. { main program }

 

In the program example, the loop will execute as long as the value typed for the variable I is not zero(0). Negative numbers may be entered along with positive ones. The SUM is declared as an INTEGER type and so can only store a limited amount. Please be careful when typing in numbers because the SUM may return a negative value if it has exceeded the positive limit of 32767.

 

When coding a WHILE..DO loop, you must have a statement which will make the condition-list evaluate to FALSE. The loop will execute as long as the condition-list evaluates to TRUE. If there isn't a statement which allows the condition-list to evaluate to FALSE, the loop will be endless! (would not stop). This is a very dangerous condition in a program.

 

Again, the BEGIN..END block in the loop is only necessary if the statements are compound. The statements can be of any valid statements in Pascal.

Other conditions which you might use includes:

 

Pseudocode

 

WHILE NOT Sorted DO

SortingRoutine;

 

WHILE NOT eof( DataFile ) DO

BEGIN

ReadDataFile;

ProcessData;

OutputResults;

END;

 

 

WHILE UserChoice = 'Y' DO

BEGIN

GetTransActionRec;

ValidateData;

if not valid then

ErrorRoutine

else begin

ProcessRecord;

OutputResults;

end;

GetUserChoice;

END;

 

These routines are only examples, of course. For them to work, the procedures used and the data types must first be defined.

 

REPEAT..UNTIL

The last loop structure available in Pascal is the REPEAT..UNTIL loop. In the REPEAT..UNTIL loop, the condition is tested AFTER the loop body executes at least once. In real life, it may be something like this:

REPEAT

exercise;

UNTIL tired

 

REPEAT

read newspaper;

UNTIL nothing else to read

 

Unlike the WHILE..DO loop, the REPEAT..UNTIL loop executes until the condition is TRUE. The loop body is clearly defined between the REPEAT and UNTIL statement. Here's an example:

 

program TestRepeatLoop;

uses CRT;

var

A, B : integer;

Choice : char;

begin { main program }

ClrScr;

repeat

Write('Type in 2 integers : ');

ReadLn( A, B );

Write(A,' is');

if A mod B <> 0 then

Write(' NOT');

WriteLn(' divisible by ',B );

Write('Another set (Y/N) ? ');

ReadLn( Choice );

until (Choice = 'N') or (Choice = 'n');

WriteLn('Thank you for using this program.');

ReadLn;

end. { main program }

 

In the example above, the loop will REPEAT UNTIL the user types in 'N' or 'n' for the variable CHOICE. Please note that the loop body executes at least once before testing to the condition which controls the loop.

 

Here is the overall syntax of the REPEAT..UNTIL loop:

 

REPEAT

loop statement body;

UNTIL condition-list;

 

and the pseudocode:

DO

loop statements

UNTIL condition-list

 

As you can see, the condition-list is tested AFTER the loop body executes. Again, like the WHILE..LOOP, there must be a statement in the loop body which makes the condition-list evaluate to TRUE.

 

After knowing how to write a loop statement and how a loop works, you should learn when to implement which type of loop. It depends a lot on the program requirements.

 

Nested loops.

Another thing to know about loops is how to nest them. Nested loops means one loop inside another. Take this for an example:

 

program MultiplicationTables;

uses CRT;

var

X, Y : integer

begin { main program }

for X := 1 to 12 do

begin

ClrScr;

for Y := 1 to 12 do

WriteLn('':30,X:3,' x ',Y:3,' = ', X * Y );

WriteLn; WriteLn;

Write('Press <ENTER>');

ReadLn;

end;

ReadLn;

end. { main program }

 

You may see this in many programs. Some processes must be accomplished using a loop, and if this process is to be repeated, it must be in another loop, which gives rise to the nested loop. Here is another example:

 

program Factorials;

uses CRT;

var

Num, Facto : integer;

I : integer;

Choice : char;

begin { main program }

ClrScr;

repeat

Write('Enter A Number :');

ReadLn( Num );

Facto := 1;

for I := 1 to Num do

Facto := Facto * I;

WriteLn('Factorial of ',Num,

' is ', Facto );

WriteLn;

Write('Another number (Y/N) ?');

ReadLn( Choice ); WriteLn; WriteLn;

until (Choice = 'N') or (Choice = 'n');

ReadLn;

end. { main program }

 

As you can see, the calculation of the factorial of a number involves a loop. If the whole process of calculating factorials is to be repeated, another loop must be used. In this case the REPEAT..UNTIL loop is used. The calculation uses a FOR..DO loop.

 

When using nested loops, especially FOR..DO loops, you should be careful that the loop doesn't execute too many times. If you were to nest two FOR..DO loops which executes ten times each, the total times that segment of the program will execute is one hundred times.

 

Some problems which do not need nested loops should not include such loops in the solution. You must check the program requirements carefully in order to determine whether the program requires a nested loop solution.

 

All in all, you must learn to control the loops for different situations. You must also learn to determine which loop is the best for a certain situation. Once all these are learnt, along with the sequence and selection construct, you can solve any programming problem, provided you have the correct tools and keywords.

 

Important :

  1. Never change the value of the loop counter in a FOR..DO loop .
  2. Make sure that there is a condition to terminate the WHILE..DO and the REPEAT..UNTIL loops.

 

Only those instructions/statements which require/need to be repeated are placed within the loop body.

1