Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Control Flow and Procedures

For, While and Repeat Loops in Pascal

Repeat work in Pascal with for..to, for..downto, while..do and repeat..until, choose the right loop, use Break, Continue and Exit, avoid infinite loops, and iterate with for..in.

A loop repeats a statement while some condition holds. Pascal has three classic loops: for when you know how many times, while when you test before each round, and repeat ... until when you must run at least once. Modern compilers add for ... in for collections. Pascal listings are read-only here; runnable demos are C stand-ins.

The for loop

PASCAL
program Counting;

var
  i: Integer;

begin
  for i := 1 to 5 do
    Write(i, ' ');
  WriteLn;
end.

Output:

TEXT
1 2 3 4 5 

for counter := start to finish do statement runs the statement once for every value from start to finish inclusive. To count down, use downto:

PASCAL
for i := 5 downto 1 do
  Write(i, ' ');            { 5 4 3 2 1 }

Rules that make Pascal's for different from C's:

  • The counter is an ordinal variable (integer, char, enumeration), never a real.
  • Start and finish are evaluated once, before the loop begins.
  • You must not change the counter inside the loop; the compiler may refuse it.
  • After the loop ends, the counter's value is undefined. Do not rely on it.
  • If start > finish the body does not run at all.
  • To run several statements, wrap them in begin ... end.

Characters and enumerations work as counters too:

PASCAL
var
  ch: Char;
begin
  for ch := 'a' to 'e' do
    Write(ch);              { abcde }
end.

Nested loops

PASCAL
var
  row, col: Integer;
begin
  for row := 1 to 3 do
  begin
    for col := 1 to 4 do
      Write(row * col:3);
    WriteLn;
  end;
end.

Output:

TEXT
  1  2  3  4
  2  4  6  8
  3  6  9 12

row * col:3 prints each number in a field three characters wide.

The while loop

while condition do statement checks the condition first; if it is false at the start, the body never runs.

PASCAL
var
  n, steps: Integer;
begin
  n := 27;
  steps := 0;
  while n <> 1 do
  begin
    if Odd(n) then
      n := 3 * n + 1
    else
      n := n div 2;
    Inc(steps);
  end;
  WriteLn('Steps: ', steps);   { 111 }
end.

Use while when the number of rounds is unknown, such as reading until the user quits or searching until something is found. Something inside the loop must eventually make the condition false, or you have an infinite loop.

The repeat ... until loop

repeat ... until condition runs the body, then checks the condition, and stops when it becomes true. The body always runs at least once, and it needs no begin/end, because repeat and until bracket the statements:

PASCAL
var
  guess: Integer;
begin
  repeat
    Write('Guess the number (1-10): ');
    ReadLn(guess);
  until guess = 7;
  WriteLn('Correct!');
end.

Notice the reversed logic compared to while: while continues while the condition is true, repeat continues while it is false. Menus and input validation are natural uses.

flowchart TD
    subgraph W["while"]
      W1{"condition?"} -->|true| W2["body"] --> W1
      W1 -->|false| W3["after"]
    end
    subgraph R["repeat..until"]
      R1["body"] --> R2{"condition?"}
      R2 -->|false| R1
      R2 -->|true| R3["after"]
    end

Figure: while tests first; repeat tests last and stops when its condition is true.

Choosing a loop

Situation Loop
Known count, or walk through a range for
Test before every round, maybe zero rounds while
At least one round, then test repeat ... until
Visit every item of an array, set or string for ... in

Break, Continue and Exit

Free Pascal and Delphi provide three helpers:

  • Break leaves the innermost loop immediately.
  • Continue jumps to the next round of the innermost loop.
  • Exit leaves the current procedure or function (or ends the program if used in the main block).
PASCAL
var
  i: Integer;
begin
  for i := 1 to 10 do
  begin
    if i mod 2 = 0 then
      Continue;            { skip even numbers }
    if i > 7 then
      Break;               { stop after 7 }
    Write(i, ' ');
  end;
  WriteLn;                 { 1 3 5 7 }
end.

For ... in

Delphi and Free Pascal (in objfpc and delphi modes) can walk through the elements of an array, a string, a set or an enumerated type without an index variable:

PASCAL
var
  c: Char;
  scores: array[1..3] of Integer = (90, 75, 88);
  s: Integer;
begin
  for c in 'Pascal' do
    Write(c, '.');                { P.a.s.c.a.l. }
  WriteLn;
  for s in scores do
    Write(s, ' ');                { 90 75 88 }
  WriteLn;
end.

The loop variable is read-only. Use an ordinary for loop when you need the position.

Common mistakes

  • Changing the loop counter inside the body.
  • Forgetting begin ... end around a multi-line body: only the first statement repeats.
  • A while whose variable is never updated (infinite loop).
  • Reversing the until condition.
  • Using a real number as the counter. If you need steps like 0.1, use an integer counter and divide.

Stand-ins in C

These programs are C; the loops correspond directly.

C C stand-in: multiplication table (nested for)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C C stand-in: while, repeat and Continue/Break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which loop always executes its body at least once?

    repeat...until tests its condition after the body, so the body runs once before the first test.
  2. 2. When does repeat ... until x > 5 stop?

    The until condition is a stop condition. The loop continues as long as it is false.
  3. 3. What does for i := 10 to 1 do WriteLn(i); print?

    to counts upward, so with start > finish the body never runs. Use downto to count down.
  4. 4. What may you not do inside a for loop body?

    Changing the counter has undefined effects (and the compiler may reject it). Use while for custom stepping.

Summary

  • for counts over an ordinal range (to or downto); the counter must not be modified, and its value is undefined afterwards.
  • while tests first; repeat ... until tests last and stops when true.
  • Break, Continue and Exit control flow; for ... in walks collections.
  • Guard against infinite loops and missing begin ... end.

Next: Procedures and Functions