Loops & Jumps

10.1 for loops

The control variable must be a local ordinal variable; it cannot be modified inside the loop.

Bounds are evaluated once before the loop starts.

There is no step value; use while or multiply (for I := 0 to 4 do X := I * 2;).

After the loop finishes normally the control variable's value is undefined (it is defined when you leave with Break).

for I := 1 to 10 do
  Write(I, ' ');           // 1 2 3 ... 10

for I := 10 downto 1 do
  Write(I, ' ');           // 10 9 ... 1

for C := 'a' to 'e' do
  Write(C);                // abcde

for Color := Low(TColor) to High(TColor) do
  Writeln(Ord(Color));

10.2 for-in loops

for-in works with arrays, strings, sets, and any type with an enumerator (Chapter 32).

var
  Ch: Char;
  N: Integer;
  Arr: array of Integer;
begin
  Arr := [10, 20, 30];        // dynamic array constant: Delphi XE7+, FPC 3.2+
  for N in Arr do
    Writeln(N);
  for Ch in 'Pascal' do
    Write(Ch, '-');
end.

10.3 while loops

Tests the condition before each iteration (may run zero times):

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('Collatz steps: ', Steps);   // 111

10.4 repeat-until

Tests the condition after each iteration (runs at least once); no begin ... end needed:

Note the inverted logic: while continues while true; repeat continues until true.

repeat
  Write('Enter a number between 1 and 10: ');
  Readln(N);
until (N >= 1) and (N <= 10);

10.5 Break, Continue, Exit, Halt

leave the innermost loop jump to the next iteration of the innermost loop leave the current procedure/function (or the main program) set the function result and leave (FPC; Delphi 2009+) terminate the program with an exit code (finalization sections still run)

function IndexOf(const A: array of Integer; Target: Integer): Integer;
var
  I: Integer;
begin
  for I := 0 to High(A) do
    if A[I] = Target then
      Exit(I);
  Result := -1;
end;
for I := 1 to 100 do
begin
  if I mod 3 <> 0 then Continue;   // skip non-multiples of 3
  if I > 30 then Break;            // stop after 30
  Write(I, ' ');
end;

10.6 goto and labels — and why to avoid them

Labels must be declared in a label section and used in the same block. goto makes control flow hard to follow, cannot jump into loops or out of routines safely, and interacts badly with try/finally. Prefer Break, Exit, a Boolean flag, or extracting the nested loops into a function that returns early.

program GotoDemo;
{$mode objfpc}
{$goto on}            // FPC requires this in objfpc mode; Delphi allows goto directly
label
  Done;
var
  I, J: Integer;
begin
  for I := 1 to 10 do
    for J := 1 to 10 do
      if I * J = 42 then
      begin
        Writeln(I, ' * ', J, ' = 42');
        goto Done;          // escape both loops at once
      end;
Done:
  Writeln('finished');
end.

10.7 Nested loops example: multiplication table

program Table;
{$mode objfpc}
var
  R, C: Integer;
begin
  Write('   ');
  for C := 1 to 9 do Write(C:4);
  Writeln;
  for R := 1 to 9 do
  begin
    Write(R:3);
    for C := 1 to 9 do
      Write(R * C:4);
    Writeln;
  end;
end.

🧪 Part I Exercises

Install FPC and Lazarus (or Delphi Community Edition). Compile "Hello, World" from both the IDE and the command line, and print the compiler version from code using {$I %FPCVERSION%} (FPC) or CompilerVersion (Delphi).

Write a program that prints Low, High, and SizeOf for every integer type, plus SizeOf for Single, Double, Extended, Currency, Char, and Boolean.

Read a temperature in Celsius and print Fahrenheit and Kelvin, formatted to two decimals with :0:2 and again with Format.

Read three integers and print them sorted, using only if statements.

Write a menu-driven calculator using case on a Char operator (+ - * / d m for div/mod), rejecting division by zero.

Print all prime numbers up to 1,000 using nested loops; then rewrite the inner loop to use Break.

Implement a number-guessing game with Random/Randomize and repeat ... until, counting attempts and validating input with TryStrToInt.

Print a right-aligned triangle and a diamond of * characters for a height entered by the user.

Write a program that reads lines from standard input until EOF and prints the number of lines, words, and characters (a mini wc).

Demonstrate the precedence trap: write an expression without parentheses that fails to compile, explain the compiler error, and fix it.