Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 2: Basic Pascal Syntax

Program structure

A Pascal program usually has these parts:

  1. Program heading: gives the program its name. It’s optional but recommended.
  2. Uses clause: lists the libraries or units the program uses. This is optional too.
  3. Declaration part: declares the program’s variables, constants, types, and procedures or functions.
  4. Begin-end block: the main block, which holds the executable statements.

Example

program ExampleProgram;

uses crt;

var
  a, b, sum: integer;

begin
  a := 10;
  b := 20;
  sum := a + b;
  writeln('Sum is: ', sum);
end.

Variables and data types

Declaring variables

You declare variables in the var section, and each one must have a data type.

var
  x: integer;
  y: real;
  z: char;
  s: string;

Common data types

  • Integer: whole numbers.
  • Real: floating-point numbers.
  • Char: single characters.
  • String: sequences of characters.
  • Boolean: True or False values.

Example

program VariableExample;

var
  age: integer;
  price: real;
  initial: char;
  name: string;
  isStudent: boolean;

begin
  age := 25;
  price := 19.99;
  initial := 'A';
  name := 'Alice';
  isStudent := true;

  writeln('Age: ', age);
  writeln('Price: ', price:0:2);
  writeln('Initial: ', initial);
  writeln('Name: ', name);
  writeln('Is Student: ', isStudent);
end.

Constants and operators

Declaring constants

Constants go in the const section. Each one must be given a fixed value.

const
  PI = 3.14159;
  MAX_SIZE = 100;

Operators

Pascal has operators for arithmetic, relational, and logical operations:

  • Arithmetic: +, -, *, /, div, mod
  • Relational: =, <>, <, <=, >, >=
  • Logical: and, or, not

Example

program OperatorExample;

var
  a, b, c: integer;
  x, y: boolean;

begin
  a := 10;
  b := 20;

  { Arithmetic Operations }
  c := a + b;
  writeln('a + b = ', c);
  c := b - a;
  writeln('b - a = ', c);
  c := a * b;
  writeln('a * b = ', c);
  c := b div a;
  writeln('b div a = ', c);
  c := b mod a;
  writeln('b mod a = ', c);

  { Relational Operations }
  if a < b then
    writeln('a is less than b');
  if a <> b then
    writeln('a is not equal to b');

  { Logical Operations }
  x := true;
  y := false;
  writeln('x and y = ', x and y);
  writeln('x or y = ', x or y);
  writeln('not x = ', not x);
end.