Loops
are programming structures that are used to repeat a block of program statements until a given condition is met.
There are three types of loops
in Pascal:
The fixed repetition loop is initialized as follows:
for _loopVariable_ := _start_ to _end_ do
begin
_block_
end;
_loopVariable_
: The variable name of the loop variable that will iterate from _start
to _end_
._start_
: The starting value of the loop._end_
: The ending value of the loop._block_
: The program statements that will be executed repeatedly.Let’s look at the code snippet below, which demonstrates the implementation of a fixed repetition loop in Pascal.
program fixedRepetetion;vari: integer;beginwriteln('Loop in forward direction');for i := 0 to 3 dobeginwriteln(i, ': Hello world!! This loop is executing in forward direction');end;for i := 3 to 2 dobeginwriteln(i, ': Hello world!! This loop is executing in forward direction');end;writeln(sLineBreak + 'Loop in backward direction');for i := 3 downto 0 dobeginwriteln(i, ': Hello world!! This loop is executing in backward direction');end;end.
down
keyword used in the for
statement.The pretest loop is initialized as follows:
while _loopCondition_ do
begin
_block_
end;
_loopCondition_
: The condition that is checked every time before executing the block
. The block
is executed only if this condition is true._block_
: The program statements that will be executed repeatedly.Consider the code snippet below, which demonstrates the implementation of a pretest loop in Pascal.
program pretest;vari: integer;begini := 0;while i < 3 dobeginwriteln (i, ': Hello World!!');i := i + 1;end;end.
i
is initialized with 0 in line 7. The while loop in line 8 checks if i<3
in line 8; this is the loop condition. The loop will iterate until this condition becomes false. As i
is incremented in line 11 each time the block executes, the while loop is executed 3 times. The third time the block is executed, i
becomes 4. Thus, the condition of while
will not be met and the loop will break.The posttest loop is initialized as follows:
repeat
begin
_block_
end;
until _loopCondition_ ;
_loopCondition_
: The condition that is checked every time after executing the block
. The loop breaks if the condition is met._block_
: The program statements that will be executed repeatedly.program posttest;vari: integer;begini := 0;repeatbeginwriteln (i, ': Hello World!!');i := i + 1;enduntil i>3;end.
A variable i
is initialized with 0 in line 6. The loop block, which is line 9-10, is executed before checking the loop condition in line 12. The loop block will execute repeatedly until the condition in line 12 is met. As i
is incremented in line 10, each time the block executes, the repeat until
loop is executed 4 times. The fourth time the block is executed, i
becomes 4. Thus, the condition of until
will be met and the loop will break.
Free Resources