Pascal: reference
A teaching language with a clear structure, ideal for your first algorithms.
Program structure
Minimal program
The program starts with program, and the body is between begin and end. (with a dot). Strings are in single quotes.
program Hello;
begin
writeln('Hello, world!');
end.Comments
Pascal is not case sensitive: Begin and begin are the same.
// single-line
{ multi-line }
(* another way *)Variables and types
Declaring variables
Variables are described in the var section before begin. Assignment is written as :=.
var age: integer; price: real; name: string; ok: boolean; letter: char; const Pi = 3.14;
Assignment and arithmetic
div is integer division, mod is the remainder, and / always gives a fraction. The notation x:0:1 sets the output format.
age := 16; price := 24.5; writeln(7 div 2, ' ', 7 mod 2, ' ', 7 / 2:0:1);
Input and output
readln and writeln
To write a single quote inside a string, double it: ''.
var name: string; age: integer;
begin
write('It''s: ');
readln(name);
readln(age);
writeln(name, ', you are ', age);
end.Conditions
if and case
No semicolon is placed before else. Several actions are combined in begin ... end.
if age < 12 then
writeln('child')
else if age < 18 then
writeln('teenager')
else
writeln('adult');
case n of
1: writeln('one');
2, 3: writeln('two or three');
else
writeln('other');
end;Logical operators
Comparison is written with =, inequality with <>. Each condition is put in parentheses.
if (x > 0) and (x < 10) then writeln('in range');
if not (x = 5) or (x > 100) then writeln('yes');Loops
for, while, repeat
repeat ... until runs at least once and ends when the condition becomes true.
for i := 1 to 5 do write(i, ' '); for i := 5 downto 1 do write(i, ' '); while n > 0 do n := n - 1; repeat n := n + 1; until n >= 3;
Arrays
One-dimensional array
The index bounds are set explicitly: [1..5].
var a: array[1..5] of integer;
i: integer;
begin
for i := 1 to 5 do
a[i] := i * i;
writeln(a[3]);
end.Procedures and functions
procedure and function
A function returns the value assigned to its name (or to the variable Result). Procedures are described before the main begin.
procedure Hello(name: string);
begin
writeln('Hello, ', name);
end;
function Add(a, b: integer): integer;
begin
Add := a + b;
end;Variable parameters
var before a parameter passes the variable itself, not a copy.
procedure Inc(var x: integer); begin x := x + 1; end;
Strings
Working with strings
String indexing starts from 1. copy(s, from, count) cuts out a part, and pos searches for a substring.
s := 'Pascal';
writeln(length(s), ' ', s[1], ' ', copy(s, 2, 3));
writeln(upcase(s[1]), pos('sc', s));
s := s + ' 7';Records
record
A record combines several fields of different types into one variable.
type
TUser = record
name: string;
age: integer;
end;
var u: TUser;
begin
u.name := 'Alex';
u.age := 16;
writeln(u.name, ' ', u.age);
end.Learn Pascal with practice
- 8 lessons
- Tasks with in-browser code checking
- Free, nothing to install