Step 1 of 5 · Reading · ~1 min
Learn
Control Flow
if/then/else — note: NO semicolon before else:
if age >= 18 then
WriteLn('adult')
else
WriteLn('minor');
The ; is a separator between statements, so a ; after WriteLn('adult') would end the if entirely and leave else with nothing to attach to — Syntax error, ";" expected or a dangling-else complaint.
Multiple statements need a begin/end block:
if x > 0 then
begin
WriteLn('positive');
WriteLn('and non-zero');
end
else
WriteLn('zero or negative');
Combining comparisons — parenthesise both sides
Logical operators are and, or, not (NOT &&, ||, !). Comparison: =, <> (not equal), <, >, <=, >=.
Pascal gives and/or a higher precedence than the comparisons — the opposite of C. So this looks right and does not compile:
{ if score > 80 and score < 89 then ... }
{ main.pas(5,14) Error: Incompatible types: got "Boolean" expected "Int64" }
The compiler read it as score > (80 and score) < 89. Wrap each comparison:
if (score > 80) and (score < 89) then
WriteLn('B');
Make this a habit: every comparison joined by and/or gets its own parentheses.
Chaining and case
For ordered bands, chain else if and let each test assume the ones above it already failed:
if score >= 90 then
WriteLn('A')
else if score >= 80 then
WriteLn('B')
else
WriteLn('C or below');
case handles a fixed set of discrete values, and its labels can be lists or ranges:
case day of
1, 2, 3, 4, 5: WriteLn('weekday');
6, 7: WriteLn('weekend');
else
WriteLn('invalid');
end;
There is no truthiness: a condition must be a boolean. if n then is a compile error; write if n <> 0 then.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…