Beginner

Control Flow in Pascal

Learn conditionals, loops, and branching in Pascal - if/else, case statements, for, while, and repeat loops with Docker-ready examples

Control flow is what turns a list of instructions into a program that can make decisions and repeat work. Pascal, as an imperative and procedural language, gives you a clean, explicit set of structured constructs for this: if/else for branching, case for multi-way selection, and three distinct loop forms (for, while, and repeat).

Pascal was designed by Niklaus Wirth specifically to teach structured programming, so its control flow avoids unstructured jumps in favor of clearly delimited blocks. Where a single statement is needed, you write it directly; where multiple statements belong together, you group them with beginend. This explicitness is a hallmark of Pascal and one of the reasons it reads so clearly.

In this tutorial you’ll learn how to branch with conditionals, select among many cases, and iterate with each of Pascal’s loop types. You’ll also see how Break and Continue control loop execution, and why Pascal offers both a top-tested while loop and a bottom-tested repeat loop.

If / Else Conditionals

The if statement evaluates a Boolean expression and executes a branch accordingly. A crucial Pascal rule: there is no semicolon before else, because the semicolon separates statements and else is part of the same if statement.

Create a file named conditionals.pas:

program Conditionals;

var
    score: Integer;
    grade: Char;

begin
    score := 78;

    { Simple if/else }
    if score >= 60 then
        WriteLn('Result: Pass')
    else
        WriteLn('Result: Fail');

    { Chained if/else if - note: no semicolon before else }
    if score >= 90 then
        grade := 'A'
    else if score >= 80 then
        grade := 'B'
    else if score >= 70 then
        grade := 'C'
    else
        grade := 'D';

    WriteLn('Grade: ', grade);

    { Grouping multiple statements with begin...end }
    if score >= 70 then
    begin
        WriteLn('You passed with a score of ', score);
        WriteLn('Keep up the good work.');
    end;
end.

Note how a single statement follows then directly, but when two statements need to run together they are wrapped in beginend. Pascal’s = is comparison inside expressions, while := is assignment.

Case Statements

When you need to branch on the value of a single ordinal expression (integers, characters, enumerated types), the case statement is clearer than a long if/else if chain. Each branch can match a single value, a list of values, or a range. The optional else (or otherwise) handles unmatched values.

Create a file named case_demo.pas:

program CaseDemo;

var
    day: Integer;
    letter: Char;

begin
    day := 6;

    case day of
        1, 2, 3, 4, 5: WriteLn('Weekday');
        6, 7:          WriteLn('Weekend');
    else
        WriteLn('Invalid day');
    end;

    letter := 'E';

    { Character ranges as case labels }
    case letter of
        'A'..'Z': WriteLn(letter, ' is an uppercase letter');
        'a'..'z': WriteLn(letter, ' is a lowercase letter');
        '0'..'9': WriteLn(letter, ' is a digit');
    else
        WriteLn(letter, ' is a symbol');
    end;
end.

The case selector must be an ordinal type, which is why strings cannot be used directly here. The 'A'..'Z' syntax matches an inclusive range of characters.

For Loops

The for loop iterates over a known range of an ordinal type. Pascal’s for is deliberately simple: you specify a start and end value, and the loop variable is incremented automatically with to (or decremented with downto). You cannot manually modify the loop variable inside the body.

Create a file named for_loops.pas:

program ForLoops;

var
    i: Integer;
    total: Integer;

begin
    { Counting up }
    Write('Counting up: ');
    for i := 1 to 5 do
        Write(i, ' ');
    WriteLn;

    { Counting down with downto }
    Write('Counting down: ');
    for i := 5 downto 1 do
        Write(i, ' ');
    WriteLn;

    { Accumulating a sum }
    total := 0;
    for i := 1 to 10 do
        total := total + i;
    WriteLn('Sum of 1 to 10: ', total);
end.

Because the bounds are evaluated once at the start, the for loop is safe and predictable. Use it whenever the number of iterations is known in advance.

While and Repeat Loops

Pascal provides two condition-controlled loops with an important difference:

  • while tests its condition before each iteration (top-tested). The body may run zero times.
  • repeatuntil tests its condition after each iteration (bottom-tested). The body always runs at least once, and it loops until the condition becomes true.

This example also shows Break (exit the loop early) and Continue (skip to the next iteration).

Create a file named while_repeat.pas:

program WhileRepeat;

var
    n: Integer;
    sum: Integer;

begin
    { while: test before the body runs }
    n := 1;
    Write('While doubling: ');
    while n <= 16 do
    begin
        Write(n, ' ');
        n := n * 2;
    end;
    WriteLn;

    { repeat: body runs at least once, loops until condition is true }
    n := 1;
    Write('Repeat countdown: ');
    repeat
        Write(n, ' ');
        n := n + 1;
    until n > 5;
    WriteLn;

    { Break and Continue }
    sum := 0;
    n := 0;
    while True do
    begin
        n := n + 1;
        if n > 10 then
            Break;          { exit the loop entirely }
        if n mod 2 = 1 then
            Continue;       { skip odd numbers }
        sum := sum + n;
    end;
    WriteLn('Sum of even numbers 1 to 10: ', sum);
end.

Use while when the loop might not need to run at all, and repeat when the body must execute once before the condition is checked (for example, validating user input after prompting).

Running with Docker

You can compile and run each example with Free Pascal in Docker, no local install required.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Pull the official image
docker pull freepascal/fpc:latest

# Run the conditionals example
docker run --rm -v $(pwd):/app -w /app freepascal/fpc:latest \
    sh -c 'fpc conditionals.pas && ./conditionals'

# Run the case example
docker run --rm -v $(pwd):/app -w /app freepascal/fpc:latest \
    sh -c 'fpc case_demo.pas && ./case_demo'

# Run the for loops example
docker run --rm -v $(pwd):/app -w /app freepascal/fpc:latest \
    sh -c 'fpc for_loops.pas && ./for_loops'

# Run the while/repeat example
docker run --rm -v $(pwd):/app -w /app freepascal/fpc:latest \
    sh -c 'fpc while_repeat.pas && ./while_repeat'

Expected Output

Running conditionals.pas:

Result: Pass
Grade: C
You passed with a score of 78
Keep up the good work.

Running case_demo.pas:

Weekend
E is an uppercase letter

Running for_loops.pas:

Counting up: 1 2 3 4 5 
Counting down: 5 4 3 2 1 
Sum of 1 to 10: 55

Running while_repeat.pas:

While doubling: 1 2 4 8 16 
Repeat countdown: 1 2 3 4 5 
Sum of even numbers 1 to 10: 30

Key Concepts

  • No semicolon before else — the semicolon separates statements, and else is part of the same if statement, so placing one before else is a syntax error.
  • beginend groups statements — a branch or loop body containing more than one statement must be wrapped in a beginend block.
  • case needs an ordinal selector — integers, characters, and enumerated types work; strings do not. Branches support value lists (1, 2, 3) and ranges ('A'..'Z').
  • for loops are bounded and safe — the range is fixed when the loop starts, and you must not modify the loop variable inside the body. Use to to count up and downto to count down.
  • while is top-tested, repeat is bottom-testedwhile may run zero times; repeatuntil always runs at least once and loops until its condition becomes true (the opposite sense of while).
  • Break and ContinueBreak exits the enclosing loop immediately, while Continue skips to the next iteration; both are Free Pascal extensions widely supported in modern Pascal.
  • = compares, := assigns — a common beginner trap; Pascal keeps the two operators distinct for clarity.

Running Today

All examples can be run using Docker:

docker pull freepascal/fpc:latest
Last updated:

Comments

Loading comments...

Leave a Comment

2000 characters remaining