Pascal - Nested Loops

Advertisements


Pascal allows using one loop inside another loop. Following section shows few examples to illustrate the concept.

The syntax for a nested for-do loop statement in Pascal is as follows:

for variable1:=initial_value1 to [downto] final_value1 do
begin
   for variable2:=initial_value2 to [downto] final_value2 do
   begin   
      statement(s);
   end;
end;   

The syntax for a nested while-do loop statement in Pascal is as follows:

while(condition1)do
begin
   while(condition2) do
   begin
      statement(s);
   end;
   statement(s);
end;

The syntax for a nested repeat ... until loop Pascal is as follows:

repeat
   statement(s);
   repeat
      statement(s);
   until(condition2);
until(condition1);

A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.

Example:

The following program uses a nested for loop to find the prime numbers from 2 to 50:

program nestedPrime;
var
   i, j:integer;
begin
   for i := 2 to 50 do
   begin
      for j := 2 to i do
         if (i mod j)=0  then
            break; {* if factor found, not prime *}
      if(j = i) then
         writeln(i , ' is prime' );
   end;
end.

When the above code is compiled and executed, it produces the following result:

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime


Advertisements
Advertisements