Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Control Flow and Procedures

If, Else and Case in Pascal

Make decisions in Pascal with if..then..else, compound statements, nested and chained conditions, the dangling else, the case statement with ranges and lists, and common semicolon mistakes.

So far programs ran straight from top to bottom. Real programs make decisions: show an error if a number is negative, pick a discount by customer type, react to a key press. Pascal has two decision statements. if chooses between two paths based on a Boolean, and case chooses among many paths based on an ordinal value.

The Pascal listings here are read-only; try them in Free Pascal or Delphi. The runnable demos are C stand-ins.

The if statement

PASCAL
program Decide;

var
  temp: Integer;

begin
  temp := 31;
  if temp > 30 then
    WriteLn('Hot day');
  WriteLn('Done');
end.

Output:

TEXT
Hot day
Done

The condition goes between if and then with no parentheses needed. If it is True, the single statement after then runs. If you need several statements, group them with begin ... end:

PASCAL
if temp > 30 then
begin
  WriteLn('Hot day');
  WriteLn('Drink water');
end;

if ... else

PASCAL
if temp > 30 then
  WriteLn('Hot')
else
  WriteLn('Not hot');

There must be no semicolon before else. In Pascal the semicolon ends a statement, and the whole if ... then ... else ... is one statement. A semicolon after WriteLn('Hot') would end the if early and leave else stranded, which is a syntax error. This is the most common beginner mistake.

With compound statements, place else right after end:

PASCAL
if temp > 30 then
begin
  WriteLn('Hot');
end
else
begin
  WriteLn('Not hot');
end;

Chains of conditions

Test several conditions in sequence with else if:

PASCAL
var
  score: Integer;
  grade: Char;
begin
  score := 83;
  if score >= 90 then
    grade := 'A'
  else if score >= 80 then
    grade := 'B'
  else if score >= 70 then
    grade := 'C'
  else
    grade := 'F';
  WriteLn('Grade: ', grade);   { Grade: B }
end.

Conditions are checked from the top; the first True wins, and the rest are skipped. Order matters: put the most specific test first.

Combine conditions with and, or and not, and remember the parentheses rule from Operators and Expressions:

PASCAL
if (age >= 18) and (age < 65) then
  WriteLn('Working age');

The dangling else

When if statements nest without begin/end, an else belongs to the nearest if:

PASCAL
if a > 0 then
  if b > 0 then
    WriteLn('both positive')
  else
    WriteLn('b is not positive');    { belongs to the inner if }

If you meant the else to go with the outer if, wrap the inner one in begin ... end. Many teams always use begin ... end to be safe.

The case statement

When one variable is compared against many values, case is clearer than a long else if chain. The selector must be an ordinal type (integer, character, enumeration, subrange, Boolean). Strings and reals are not allowed.

PASCAL
var
  day: Integer;
begin
  day := 6;
  case day of
    1..5: WriteLn('Weekday');
    6, 7: WriteLn('Weekend');
  else
    WriteLn('Not a valid day');
  end;
end.

Output:

TEXT
Weekend

Each branch is a list of constants (6, 7), a range (1..5) or both, followed by a colon and one statement (use begin ... end for more). The optional else catches everything else; without it an unmatched value does nothing. The whole statement ends with end;.

Case works nicely with enumerations and characters:

PASCAL
type
  TShape = (Circle, Square, Triangle);
var
  s: TShape;
  c: Char;
begin
  s := Square;
  case s of
    Circle:   WriteLn('Round');
    Square:   WriteLn('Four sides');
    Triangle: WriteLn('Three sides');
  end;

  c := 'k';
  case c of
    '0'..'9':       WriteLn('digit');
    'a'..'z', 'A'..'Z': WriteLn('letter');
    ' ':            WriteLn('space');
  else
    WriteLn('other');
  end;
end.

Labels must not overlap: listing 'a' on its own and again inside 'a'..'z' makes Free Pascal report "Duplicate case label". Test special cases such as vowels with an if before the case.

flowchart TD
    A["case selector of"] --> B{"match 1..5 ?"}
    B -->|yes| C["Weekday"]
    B -->|no| D{"match 6, 7 ?"}
    D -->|yes| E["Weekend"]
    D -->|no| F["else branch"]

Figure: a case statement checks the labels and runs exactly one branch.

When to use which

Situation Use
One condition, two outcomes if ... else
Ranges of reals, complex conditions if ... else if chain
One ordinal value, many exact values or ranges case
Strings if chain (or CompareStr/AnsiIndexStr helpers)

Common mistakes

  1. Semicolon before else. Remove it.
  2. = versus :=. if x := 5 then is an error; compare with =.
  3. Forgetting begin ... end for a multi-statement branch: only the first statement is conditional.
  4. Empty then. if x > 5 then; ends the if with an empty statement and the following line always runs.

Stand-ins in C

The C versions use the same logic with braces. These programs are C.

C C stand-in: grade with else-if

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: a case-like switch with ranges

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. Why is this a syntax error? if x > 0 then WriteLn('a'); else WriteLn('b');

    The semicolon terminates the whole if statement, so the else has no matching if. Remove the semicolon before else.
  2. 2. Which type may NOT be used as a case selector?

    Case needs an ordinal selector. Strings and reals are not ordinal, so use an if chain for them.
  3. 3. In case n of 1..3: A; 4, 5: B; else C; end;, which branch runs for n = 5?

    5 matches the label list 4, 5, so branch B runs.
  4. 4. In nested ifs without begin/end, which if does an else belong to?

    The else attaches to the nearest unmatched if. Use begin/end to change that.

Summary

  • if cond then stmt else stmt; no semicolon before else; group several statements with begin ... end.
  • Chain tests with else if; the first true condition wins.
  • case selects by ordinal value with lists, ranges and an optional else; strings are not allowed.
  • Watch for then; and for dangling else.

Next: For, While and Repeat Loops