If Else in Pascal

Our first example demonstrates branching with if and else statements in Pascal. Here’s the full source code:

program IfElseExample;
uses Crt;

var
  num: Integer;

begin
  { Here's a basic example. }
  if 7 mod 2 = 0 then
    WriteLn('7 is even')
  else
    WriteLn('7 is odd');

  { You can have an if statement without an else. }
  if 8 mod 4 = 0 then
    WriteLn('8 is divisible by 4');

  { Logical operators like 'and' and 'or' are often useful in conditions. }
  if (8 mod 2 = 0) or (7 mod 2 = 0) then
    WriteLn('either 8 or 7 are even');

  { A variable can be declared before conditionals; it will be available in all branches. }
  num := 9;
  if num < 0 then
    WriteLn(num, ' is negative')
  else if num < 10 then
    WriteLn(num, ' has 1 digit')
  else
    WriteLn(num, ' has multiple digits');
end.

To run the program, save it as if_else_example.pas and compile it using a Pascal compiler such as Free Pascal:

$ fpc if_else_example.pas
$ ./if_else_example
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Pascal, you need to use then after the condition in an if statement, and begin/end blocks are required for multiple statements within a branch. The else if is written as else if in Pascal, not as a single keyword like in some other languages.

Pascal uses and and or for logical operators instead of && and ||. The modulo operator is mod in Pascal.

Unlike some modern languages, Pascal doesn’t have a ternary operator, so you’ll need to use a full if statement even for basic conditions.

Pascal’s WriteLn function is used for console output, similar to fmt.Println in the original example.

Remember that Pascal is case-insensitive, so WriteLn and writeln are equivalent. However, it’s good practice to maintain consistent capitalization for readability.