DMarlon Studio

Lesson 8 · 8 of 20

Booleans and comparisons · Pascal

Compare values in Pascal with =, <>, < and >, and combine conditions with and, or, not and xor to decide who rides the roller coaster.

Pascal · Booleans and comparisons in DMarlon Studio: the example's code and its output in the terminal

A comparison gives a `Boolean`: True or False, which WriteLn prints as TRUE and FALSE. The operators are =, <> (not equal), <, >, <= and >=. Remember: = compares and := assigns.

Conditions are combined with `and` (both must hold), `or` (one is enough) and `not` (turns it around). The result can be stored in a variable, such as canRide or discount, and used later.

The key point: in Pascal, and and or have higher precedence than comparisons, so each comparison needs its own brackets: (height >= 140) and hasTicket. Without them, age < 14 or age >= 65 would be read as age < (14 or age) >= 65 and would not compile.

`xor` is true when exactly one side is true. Free Pascal also uses short-circuit evaluation for and and or: if the first side already decides the result, the second is not checked.

(age >= 10) and (age <= 12) checks that the age falls within a range, the most common use inside an if.

Code · main.pas

program main;var  age, height: Integer;  hasTicket, isMember, canRide, discount: Boolean;begin  age := 12;  height := 145;  hasTicket := True;  isMember := False;  // = compares (:= assigns) and <> means "not equal".  WriteLn('Is the age 12? ', age = 12);  WriteLn('Is the age not 18? ', age <> 18);  WriteLn('Taller than 1.50 m? ', height > 150);  // With and/or, each comparison goes in its own brackets.  canRide := (height >= 140) and hasTicket;  WriteLn('Can ride the roller coaster? ', canRide);  discount := (age < 14) or (age >= 65) or isMember;  WriteLn('Gets a discount? ', discount);  WriteLn('Pays full price? ', not discount);  // xor is true when exactly one side is true.  WriteLn('Ticket or card, but not both? ', hasTicket xor isMember);  if (age >= 10) and (age <= 12) then    WriteLn('Category: junior');end.

Output · fpc main.pas && ./main

Is the age 12? TRUE
Is the age not 18? TRUE
Taller than 1.50 m? FALSE
Can ride the roller coaster? TRUE
Gets a discount? TRUE
Pays full price? FALSE
Ticket or card, but not both? TRUE
Category: junior

Key points

  • Comparisons give True or False.
  • <> means «not equal to».
  • and, or, not and xor combine Booleans.
  • Put each comparison in brackets when using and or or.

Exercise

Add a withAdult: Boolean variable and change canRide so children under 8 can only ride with an adult: (height >= 140) and hasTicket and ((age >= 8) or withAdult).