UNIHIVE

Study Hub UNIPORT CSC 288

CSC 288 · Structured Programming

Pascal program structure, types and expressions

The shape of a Pascal program, identifiers, standard types, constants and variables, operators, input and output.

Our notes

2 min read

Shape of a program

program Average;
{ Reads three scores and prints their average }
const
  Count = 3;
var
  a, b, c: integer;
  avg: real;
begin
  write('Enter three scores: ');
  readln(a, b, c);
  avg := (a + b + c) / Count;
  writeln('Average = ', avg:0:2)
end.
Input 60 72 81 gives: Average = 71.00

Parts: heading, declarations (label, const, type, var, procedures and functions), then the compound statement between begin and end, finished by a full stop.

Identifiers and rules

Start with a letter, then letters, digits (and underscores in Free and Turbo Pascal). Pascal is not case sensitive: Score and SCORE are the same. Reserved words (begin, end, if, while, var) cannot be names. Statements are separated by semicolons, so the statement before end needs none (one there is allowed: it adds an empty statement).

Standard types

TypeValuesExample
integerwhole numbers (16 or 32 bits depending on compiler)42
realnumbers with fractions3.75
booleantrue, falsetrue
charone character'A'
stringtext (Turbo and Free Pascal)'Choba'

Ordinal types (integer, char, boolean, enumerations, subranges) have a next and previous value: succ, pred, ord.

User-defined types

type
  Day = (Mon, Tue, Wed, Thu, Fri);
  Score = 0..100;
A subrange like Score lets the compiler catch out-of-range values (with range checking on, {$R+}).

Operators

  • Arithmetic: + − * / (real result), div (integer quotient), mod (remainder).
  • Relational: = <> < <= > >=.
  • Boolean: not, and, or.

Precedence: not; then * / div mod and; then + − or; then relations. So comparisons joined by and must be bracketed: if (x > 0) and (x < 10) then ...
Example: 17 div 5 = 3, 17 mod 5 = 2, 17 / 5 = 3.4.

Input and output

read and readln take input; write and writeln give output. Field widths format numbers: writeln(x:8:2) prints a real in 8 places with 2 decimals.

Exams usually ask

  • Write a short program with declarations and input/output.
  • Evaluate expressions with div, mod and precedence.
  • Explain the rules for identifiers and semicolons.

Common mistake

Writing if x > 0 and x < 10 then. Because and binds tighter than >, Pascal reads it as x > (0 and x) < 10 and gives a type error; bracket each comparison.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

No reading links here yet

Our team adds free books, videos and practice for each topic, and opens every link before it goes up.

All CSC 288 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.