Tuesday, 28 August 2012

Pascal Programming Lesson #6 - Loops


Loops are used when you want to repeat code a lot of times. For example, if you wanted to print "Hello" on the screen 10 times you would need 10 Writeln commands. You could do the same thing by putting 1 Writelncommand inside a loop which repeats itself 10 times.

There are 3 types of loops which are the for loop, while loop and repeat until loop.

For loop

The for loop uses a loop counter variable, which it adds 1 to each time, to loop from a first number to a last number.

program Loops;

var
   i: Integer;

begin
   for i := 1 to 10 do
      Writeln('Hello');
end.

If you want to have more than 1 command inside a loop then you must put them between a begin and an end.

program Loops;

var
   i: Integer;

begin
   for i := 1 to 10 do
      begin
         Writeln('Hello');
         Writeln('This is loop ',i);
      end;
end.

While loop

The while loop repeats while a condition is true. The condition is tested at the top of the loop and not at any time while the loop is running as the name suggests. A while loop does not need a loop variable but if you want to use one then you must initialize its value before entering the loop.

program Loops;

var
   i: Integer;

begin
   i := 0;
   while i <= 10
      begin
         i := i + 1;
         Writeln('Hello');
      end;
end.

Repeat until loop

The repeat until loop is like the while loop except that it tests the condition at the bottom of the loop. It also doesn't have to have a begin and an end if it has more than one command inside it.

program Loops;

var
   i: Integer;

begin
   i := 0;
   repeat
      i := i + 1;
      Writeln('Hello');
   until i = 10;
end.

If you want to use more than one condition for either the while or repeat loops then you have to put the conditions between brackets.

program Loops;

var
   i: Integer;
   s: String;

begin
   i := 0;
   repeat
      i := i + 1;
      Write('Enter a number: ');
      Readln(s);
   until (i = 10) or (s = 0);
end.

Break and Continue

The Break command will exit a loop at any time. The following program will not print anything because it exits the loop before it gets there.

program Loops;

var
   i: Integer;

begin
   i := 0;
   repeat
      i := i + 1;
      Break;
      Writeln(i);
   until i = 10;
end.

The Continue command will jump back to the top of a loop. This example will also not print anything but unlike the Break example, it will count all the way to 10.

program Loops;

var
   i: Integer;

begin
   i := 0;
   repeat
      i := i + 1;
      Continue;
      Writeln(i);
   until i = 10;
end.

0 comments:

Post a Comment