typestar

if and case in Delphi

A fog signal chooses its pattern from visibility, then a month picks the watch.

program IfCase;
var
  Visibility: Integer = 400;    // a global may carry an initial value
  Month: Integer = 11;
begin
  if Visibility < 200 then      // the first true test in a ladder wins
    WriteLn('horn: continuous')
  else if Visibility < 1000 then
  begin
    WriteLn('horn: every 30 seconds');
    WriteLn('lamp: full power');  // begin..end groups both statements
  end
  else                           // no semicolon before an else
    WriteLn('horn: silent');
  case Month of
    12, 1, 2: WriteLn('winter watch');
    3..5: WriteLn('spring watch');   // a case label may be a range
  else WriteLn('open season');
  end;
end.

How it works

  1. if Visibility < 200 then is tested first, and the else if below it catches 400.
  2. The middle branch groups two WriteLn calls, and no semicolon precedes else.
  3. case Month of matches the labels 12, 1, 2 and the range 3..5 before its else.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
595
Tokens
103
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 1 of 3 in Control flow, step 7 of 27 in Language basics.

← Previous Next →