Pascal is used here as a teaching language, not as the final goal.
The useful thing to learn is imperative programming:
variables, statements, control flow, procedures, recursion, data
structures, files, testing, and modularity.
The dialect assumed in these notes is Free Pascal.
Pascal has many dialects, so portable code should avoid relying on
accidental features unless they are clearly Free Pascal features.
Chapter Map
first Pascal programs, expressions, variables, input, branches, and
loops
subprograms, recursion, structured programming, characters, and text
data
types, arrays, records, strings, command-line arguments, files, and
pointers
linked structures, more recursion, formatting style, testing,
debugging, and modules
Detailed notes - 2: Pascal and the beginnings of programming
1
Pascal:
introduced by Niklaus Wirth in 1970 for teaching programming
used here to move from discussing computers to writing programs
2
Pascal dialects:
different implementations added extensions and changed the language
the name alone does not identify one precise set of rules
distinguish the original language, standards, and implementation dialects
3
Free Pascal:
compiler begun by Florian Paul Klaempfl in 1993
supports several Pascal dialects and operating systems
supplies many facilities beyond those used in this book
4
limited teaching subset:
learn imperative programming through Pascal examples
practise structured programming, recursion, pointers, and other basics
prepare for C and C++; learning every Free Pascal extension is unnecessary
5
further study and choice of professional tools:
readers can study other Pascal facilities independently
the author's preference for other languages is a later practical question
6
main subject = programming
Pascal supplies the examples and a way to experiment
First Programs
A Pascal program is ordinary text, usually saved with the
.pas suffix and compiled with fpc:
fpc hello.pas
./hello
A minimal program has a heading, a main block, and a final dot:
program hello;
begin
writeln('Hello, world!');
end.
Important syntax:
Fragment
Meaning
program hello;
Program heading and program name
begin ... end
Operator brackets: a block of statements
writeln(...)
Output followed by a newline
'text'
String literal
. after final end
End of the whole program
write prints without a newline; writeln
prints and then ends the line. read and readln
read values from standard input.
Compiler messages matter:
Kind
Meaning
Fatal / Error
Compilation failed
Warning
Legal code, but probably suspicious
Note
Legal code, but the compiler noticed something unusual
Read the first error first. Later errors are often consequences of
the first one.
Detailed notes - 2.1: First programs
1
CPU executes machine code
writing it directly is laborious
source code: text following a programming language's rules
compiler: translates the program into another representation
interpreter: carries out the actions described by the program
2
Pascal workflow used here:
write plain source text in a text editor
save with a .pas suffix
compile with fpc
run the resulting executable
3
experiment directory:
mkdir firstprog; cd firstprog
ls checks its contents
shell prompt identifies user, host, and current directory
4
start an editor with the intended filename:
vim hello.pas, joe hello.pas, or nano hello.pas
a new file appears when its contents are first saved
5
first program: print Hello, world!
program hello; introduces the program and its name
identifiers name program entities
header ends with a semicolon
the book keeps the header even where the compiler permits omission
6
begin:
starts the main body
later programs also contain declarations and subprograms outside it
7
writeln('Hello, world!'):
prints its arguments
ln means a newline follows the output
8
terminology of built-in I/O:
the author calls writeln a statement because of its special syntax
arbitrary argument counts and formatting directives need compiler support
its identifier status also explains the common name built-in procedure
9
string literal:
characters enclosed in apostrophes represent themselves
without quotes, words are interpreted as program identifiers/syntax
10
end.:
end closes the main body
final dot terminates the program
11
save and inspect the source:
ls checks that hello.pas exists
cat hello.pas displays this short file
Tab completion can supply its filename
12
compile: fpc hello.pas
Error / Fatal: compilation cannot produce the requested program
warning: valid syntax may still describe suspicious behavior
note: a less severe observation
the book's particular old linker warning is specific to its environment
13
example errors:
writenl: unknown identifier
omitted final dot: compiler reaches the end while expecting '.'
Fatal stops further processing
14
diagnostic position:
filename(row,column) identifies where the problem was detected
unexpected end-of-file can be reported after the last written row
15
learn the editor's jump-to-number command:
diagnostic positions make locating errors much faster
16
compilation products:
hello.pas: source text
hello.o: object module used by the linker
hello: executable; ls -l shows execute permission
runtime support explains why a tiny source can produce a larger executable
17
run the local executable: ./hello
'.' means the current directory
a command without a slash is searched through PATH
current directory need not be in PATH
18
sequential statements:
execute in their written order
semicolon separates neighboring Pascal statements
end is a delimiter; a semicolon before it is unnecessary
19
write versus writeln:
two writeln calls produce two output lines
write prints without adding a newline
after write, the next shell prompt can appear immediately after the text
source changes require recompilation before rerunning
20
mixed output example:
write('First'); writeln('Second') -> FirstSecond, then newline
write('Third'); writeln('Fourth') -> ThirdFourth, then newline
output does not insert separators unless requested
21
English terminology:
statement: a language construction prescribing an action
operator: an operation such as +, *, or a comparison
Russian 'оператор' usually means statement in programming
22
mathematical terminology differs:
Russian mathematical 'оператор' retains the meaning of English operator
23
keep the programming terms distinct:
this becomes especially relevant to the C++ keyword operator
24
source layout in the examples:
program header and outer begin/end start at the left margin
statements inside the body are indented by four spaces
major elements occupy separate lines
25
compiler generally ignores these layout choices:
many untidy arrangements compile identically
confusing layout makes even one's own unfinished code difficult to follow
26
readability:
programmers spend much time reading and modifying existing code
source must communicate its structure and behavior to people
27
structural indentation:
shift nested constructions right relative to their containing construction
expose the nesting at a glance
28
indent width in the book = four spaces
different projects use different conventions
width should make nesting visible without wasting horizontal space
29
consistency:
keep one indentation convention throughout the program
apply the same consistency to other formatting decisions
writeln(17 div 5); { 3 }
writeln(17 mod 5); { 2 }
writeln(17 / 5); { real value }
Pascal is strongly typed: each value and variable has a type, and the
compiler uses types to reject many meaningless operations before the
program runs.
Detailed notes - 2.2.1: Arithmetic operations and the idea of type
1
write / writeln also print computed values:
writeln(175*113) prints 19775
comma-separated arguments can combine labels and expressions
'175*113' prints those characters; 175*113 computes their product
2
arithmetic and precedence:
+ addition; - subtraction; * multiplication
multiplication binds more tightly than addition/subtraction
10 + 5 * 7 = 45; (10 + 5) * 7 = 105
3
unary operators:
- changes the sign of one operand
+ leaves its operand unchanged
4
ordinary division /:
produces a floating-point result even for two integer operands
writeln(14/7:7:3) prints two spaces followed by 2.000
10
integer division:
div: integer quotient
mod: remainder
27 div 4 = 6; 27 mod 4 = 3
Variables,
Initialization, and Assignment
Variables are declared before the main block:
program sum2;
var
a, b, s: integer;
begin
readln(a, b);
s := a + b;
writeln(s);
end.
:= means assignment. It changes the value stored in a
variable.
Do not confuse:
Symbol
Meaning
:=
Assignment
=
Equality test
A variable should be assigned a meaningful value before it is read.
Reading an uninitialized variable is a programming error even if the
compiler happens to accept the program.
Detailed notes - 2.2.2: Variables, initialization, and assignment
1
fixed literals limit a program to one particular set of inputs
more useful programs solve the same task for different data
2
general solution needs values supplied at run time:
read input, store it in memory, then process it
Pascal provides variables for this purpose
3
variables across languages:
imperative languages use broadly similar mutable storage
other paradigms can use variables differently or omit them
4
variable names are identifiers:
letters, digits, underscore; cannot start with a digit
Pascal ignores letter case in identifiers
use consistent spelling despite this case insensitivity
5
variable holds a value:
referring to it in an expression supplies its current value
6
typed variables:
each Pascal variable has a declared type
its stored values and expressions referring to it have that type
in the book's mode, integer ranges from -32768 to 32767
7
declaration and initialization:
var x, y: integer; flag: boolean;
declarations precede the main body
x: integer = 500 supplies an initial value in this dialect
explicitly establish a value before reading a variable
compiler warnings do not detect every uninitialized read
8
assignment: x := expression
evaluate the right-hand side, then store its value in x
the old value is replaced
successive assignments 25, 36, 49 produce those values when printed
x := x + 5 uses the old x to calculate its new value
Identifiers name programs, variables, constants, types, procedures,
functions, and fields.
Rules:
use Latin letters, digits, and _
start with a letter
do not use reserved words such as program,
var, begin, end, if,
then, else, while,
do
Pascal is case-insensitive, so Count,
count, and COUNT are the same identifier
Choose names by meaning, not by keyboard convenience.
Detailed notes - 2.2.3: Identifiers and reserved words
1
one naming syntax for different entities:
program, variables, and later user-defined entities use identifiers
letter/underscore followed by letters, digits, or underscores
2
language also supplies existing words:
program, var, begin, end, div, mod
write, writeln, integer, boolean
3
reserved words:
part of the language grammar
cannot be reused as names for program entities
4
predefined identifiers:
some built-in names can be hidden by a declaration
declaring a variable named integer can hide the type name
such reuse makes code confusing and should be avoided
5
classification depends on dialect:
historical Pascal and Free Pascal do not classify every built-in word alike
do not infer reserved-word status merely from frequent built-in use
Input
read reads values and leaves the rest of the line
available. readln reads values and then finishes the
current input line.
var
x, y: integer;
begin
readln(x, y);
writeln(x + y);
end.
For simple programs, prefer readln: it usually matches
line-oriented input better.
Detailed notes - 2.2.4: Input for later processing
1
input changes variables:
obtains data from an external source
stores the received values for subsequent processing
2
read(x):
reads a value of x's type into x
terminal input normally becomes available after Enter
square example first reads an integer
3
read -> calculate -> print:
x := x*x replaces the input with its square
writeln(x) prints the result
waiting for input is different from a hung program
4
standard input need not be a keyboard:
echo 37 > num.txt creates input data
./square < num.txt reads it and prints 1369
changing the file changes the data without changing the program
5
pipes and redirection:
echo 37 | ./square supplies another program's output as input
> result.txt sends the result to a file
shell arranges streams before starting the program
program uses standard input/output without needing to know their endpoints
Integer Width
Fixed-size integer types can overflow. If the mathematical result
does not fit in the chosen type, the program result is not the
mathematical result.
Common Free Pascal integer types:
Type
Typical meaning
integer
Default signed integer, implementation-dependent size
longint
Signed 32-bit integer
int64
Signed 64-bit integer
byte
Unsigned 8-bit integer
word
Unsigned 16-bit integer
Use a type large enough for all intermediate results, not only for
the final answer.
Detailed notes - 2.2.5: Beware insufficient range
1
fixed-width integer overflow:
in the book's 16-bit integer mode, 200*200 does not fit
the unchecked example produces -25536 instead of 40000
2
bit-level explanation:
40000 - 65536 = -25536
the same 16 bits are interpreted as a signed result
overflow behavior and checks depend on compiler settings
3
choose a type with enough range:
181^2 fits a signed 16-bit integer; 182^2 does not
longint: signed 32-bit, -2^31 through 2^31-1
changing the declaration and recompiling extends the usable range
46340^2 fits; 46341^2 exceeds it
4
wider and unsigned types still have limits:
int64: signed 64-bit; 3037000499^2 fits
qword: unsigned 64-bit, 0 through 2^64-1
gains one positive-value bit by giving up negative values
(2^32-1)^2 fits qword; (2^32)^2 does not
the unchecked example wraps the latter result to zero
Sequential Statements
The simplest program structure is a sequence:
readln(a);
b := a * a;
writeln(b);
Pascal semicolons separate statements. A semicolon before
end is usually accepted as an empty extra statement, but a
semicolon before else changes the syntax and is normally
wrong.
Detailed notes - 2.2.6: A simple statement sequence
1
statements finish before the next one begins:
writeln('First'); readln; writeln('Second')
readln without arguments consumes the rest of an input line
on the terminal it can wait for Enter
2
two pauses in sequence:
first Enter permits Second to be printed
second Enter permits Third and program termination
3
final readln in some teaching examples:
historically used to keep a separately opened console window visible
it performs real input; it is not required Pascal boilerplate
4
address window lifetime in the execution environment:
launch from an existing terminal or configure the development environment
a pause should have an explicit purpose
5
author's concern about teaching through an IDE:
one-key execution can conceal compilation and executable files
compilation produces a program, as well as reporting errors
6
exercise:
print a poem one line at a time
wait for Enter between successive lines
7
flowcharts:
rectangle: action
small circle: start/end in these diagrams
diamond: condition
arrows show execution order
Branching
Full form:
if x < 0 then
writeln('negative')
else
writeln('non-negative');
Without else:
if x = 0 then
writeln('zero');
Use begin ... end when a branch contains more than one
statement:
if x < 0 then begin
writeln('negative');
x := -x;
end;
Detailed notes - 2.2.7: Branching
1
useful control flow depends on conditions:
select actions, repeat actions, or call other parts of a program
2
branching tests a condition at run time:
full branch: one action for true, another for false
incomplete branch: action for true, nothing for false
3
if is a statement containing other statements:
absolute-value example prints x when x > 0, otherwise -x
zero is handled by the second branch
4
whole if/then/else construction = one statement
its branch statements are nested inside it
5
condition after if must be boolean:
comparison such as x > 0 computes true or false
6
syntax:
if condition then statement1
optionally add else statement2
then separates the condition from its action
7
incomplete-branch version of absolute value:
if x < 0 then x := -x;
writeln(x) executes afterward in either case
mathematical absolute value of the minimum signed integer needs a wider type
8
indent branch contents one level beyond the if:
nesting becomes visible without tracing the syntax character by character
9
no semicolon before else:
semicolon ends/separates the preceding statement
else belongs to the same if and cannot stand alone
Detailed notes - 2.2.8: Compound statements
1
one syntactic statement slot may need several actions
for example, an if branch
2
swap example:
ensure a <= b by swapping only when a > b
temporary t preserves a while its storage is overwritten
requires three assignments
3
begin ... end groups statements into one compound statement:
t := a; a := b; b := t
put this block in the conditional branch
4
book's block layout:
begin on the next line, aligned with if
body indented one level
end aligned with the construction it closes
5
another permitted layout:
begin on the same line as then
end still aligns with the start of the if
matching indentation exposes the full construction
6
third layout:
indent begin/end beneath if and the body one level farther
author regards this as permissible but does not recommend it
Boolean Expressions
Boolean values have type boolean and values
true or false.
Operation
Meaning
not
Negation
and
Conjunction
or
Disjunction
xor
Exclusive OR
=, <>, <,
<=, >, >=
Comparisons
Example:
if (x >= 0) and (x <= 100) then
writeln('inside range');
Parentheses are cheap; use them to make precedence obvious.
Detailed notes - 2.2.9: Boolean expressions and the boolean type
1
comparison operators:
>, <, =, <>, >=, <=
each computes a boolean result
2
boolean expressions are evaluated like arithmetic expressions:
x + 1 produces a number
x > 1 produces true or false
3
boolean variable:
stores a logical value
can be assigned a boolean expression
referring to the variable itself supplies a condition
4
example:
negative := x < 0;
if negative then x := -x
5
logical operators:
not: negation; and: conjunction; or: disjunction; xor: exclusive or
flag := not flag toggles a boolean
parenthesize comparisons: (k >= 0) and (k <= 9)
Pascal's logical connectives bind more tightly than comparisons
6
combine conditions:
((c >= 'A') and (c <= 'Z')) or ((c >= 'a') and (c <= 'z'))
tests ASCII Latin-letter ranges
some redundant parentheses can improve readability
7
avoid comparing a boolean to true/false:
B instead of B = true
not B instead of B = false
meaningful names make conditions read naturally: if found then
Section test (1 file) - 2.2.9: Boolean expressions and the boolean type
program diamond;
var
n, k, h, i: integer;
begin
repeat
write('Enter the diamond''s height (positive odd): ');
readln(h)
until (h > 0) and (h mod 2 = 1);
n := h div 2;
for k := 1 to n + 1 do
begin
for i := 1 to n + 1 - k do
write(' ');
write('*');
if k > 1 then
begin
for i := 1 to 2*k - 3 do
write(' ');
write('*');
end;
writeln
end;
for k := n downto 1 do
begin
for i := 1 to n + 1 - k do
write(' ');
write('*');
if k > 1 then
begin
for i := 1 to 2*k - 3 do
write(' ');
write('*')
end;
writeln
end
end.
program DiamondProc;
procedure PrintSpaces(count: integer);
var
i: integer;
begin
for i := 1 to count do
write(' ')
end;
procedure PrintLineOfDiamond(k, n: integer);
begin
PrintSpaces(n + 1 - k);
write('*');
if k > 1 then
begin
PrintSpaces(2*k - 3);
write('*')
end;
writeln
end;
var
n, k, h: integer;
begin
repeat
write('Enter the diamond''s height (positive odd): ');
readln(h)
until (h > 0) and (h mod 2 = 1);
n := h div 2;
for k := 1 to n + 1 do
PrintLineOfDiamond(k, n);
for k := n downto 1 do
PrintLineOfDiamond(k, n)
end.
Functions
A function computes a value:
function Square(x: integer): integer;
begin
Square := x * x;
end;
Call:
writeln(Square(12));
In Pascal, assigning to the function name sets the return value.
Detailed notes - 2.3.2: Functions
1
function is a subprogram returning a value:
has header, optional local declarations, and body
call can occur within a larger expression
2
Cube example:
function Cube(x: real): real;
body assigns Cube := x*x*x
type after the parameter list specifies the result type
3
function call is a typed expression:
Cube(b+3.5) evaluates its argument, runs the function, supplies its result
a := Cube(b+3.5) - 17.1 then subtracts and stores the result
4
arguments can be variables or other expressions:
a := Cube(a) computes from the old a before replacing it
avoid unnecessary run-time work for already known constant results
5
Free Pascal allows discarding a function result:
author deliberately avoids this style in the course
6
returning value and control:
function must establish the result on every path that returns normally
caller receives that result when execution resumes
7
assign to the function's name to set its result:
iterative Fibonacci example uses q = 0 and r = 1 initially
each iteration: p := q; q := r; r := p+q
r holds the current Fibonacci number, q its predecessor
iterate from 2 through n; return r; n = 1 needs no iterations
8
separate exceptional/base input:
example returns zero for n <= 0
author recommends one result-setting assignment on each execution path
multiple assignments are permitted by Pascal; this is a style restriction
Fibonacci values still must fit the chosen integer type
Boolean Functions
Boolean functions are useful for naming conditions:
function IsDigit(c: char): boolean;
begin
IsDigit := (c >= '0') and (c <= '9');
end;
Then the main code reads more directly:
if IsDigit(ch) then
writeln('digit');
Detailed notes - 2.3.3: Boolean functions and conditions
1
boolean-returning function:
call itself is a boolean expression
can directly serve as an if/while condition
a meaningful predicate name can replace a long condition
2
IsLatinLetter(ch):
returns membership in 'A'..'Z' or 'a'..'z'
use if IsLatinLetter(c) then
reusable and clearer than repeated range comparisons
comparing the call to true adds nothing
3
return the boolean expression directly:
IsDigit := (ch >= '0') and (ch <= '9')
if condition then true else false merely reconstructs condition
Value and Variable
Parameters
Ordinary parameters receive values. Changing the parameter inside the
subprogram does not change the caller's variable.
var parameters receive variables themselves:
procedure Swap(var a, b: integer);
var
t: integer;
begin
t := a;
a := b;
b := t;
end;
Use var parameters for output parameters or when a
procedure must modify the caller-visible object.
Detailed notes - 2.3.4: Variable parameters
1
value parameter:
local variable initialized with the evaluated argument
p(2*a+7) passes the result, not the expression's constituent storage
changing local x does not alter caller's a
2
passing a variable by value still copies its value:
p(a) does not create a lasting connection between x and a
3
need for output parameters:
one subprogram may calculate several results together
x^2, x^3, x^4, x^5 need four successive multiplications
independent functions could repeat work
4
variable parameter:
formal name refers to the actual variable itself
updates through that name change caller's storage
5
var in a parameter declaration:
applies to that group up to the next semicolon/closing parenthesis
procedure p(var x, y: integer; z: integer; var k: real)
x, y, k by reference; z by value
6
powers example:
powers(x: real; var quad, cube, fourth, fifth: real)
Detailed notes - 2.6.7: User-defined types and subprogram parameters
1
user-defined parameters require attention to type identity and copying
2
name ordinary parameter/result types first:
type MyRange = 1..100; then procedure p1(b: MyRange)
an inline 1..100 in that ordinary parameter position is rejected
special open-array facilities have their own syntax outside this discussion
3
large value parameters/results can be expensive:
copying takes time
call-local storage can place pressure on the stack
4
variable parameters avoid copying the object:
callee receives access to the original storage through its address
requires only pointer-sized call information
5
author's recommendation:
avoid unnecessary transfers of large structures
when passing them, consider reference-based interfaces
where available, read-only reference parameters express nonmutation more accurately
6
size guideline is heuristic:
a few machine words differ from hundreds of bytes or kilobytes
frequency, target architecture, and compiler behavior determine actual cost
Globals and Side Effects
A global variable is visible outside one subprogram. Globals are
sometimes convenient, but they create hidden connections between parts
of the program.
Prefer parameters and return values when possible. A function is
easiest to understand when the same arguments always produce the same
result and no hidden state changes.
Detailed notes - 2.3.5: Global variables
1
scope:
local declarations are visible within their subprogram
program-level declarations are visible from their declaration onward
declare main-body-only data immediately before that body where dialect permits
2
global communication is possible but usually undesirable:
subprogram can read/write an earlier program-level variable
prefer explicit input parameters, function results, and output parameters
3
hidden state makes calls harder to understand:
arguments are visible at the call; global dependencies are not
previous activity can change later behavior unexpectedly
4
many potential writers complicate debugging:
finding who corrupted a global value can require searching the whole program
5
global singleton data obstructs multiple instances:
one game board/database today may become several tomorrow
pass the relevant object's state explicitly to support independent instances
Detailed notes - 2.3.6: Functions and side effects
1
Pascal functions can perform more than calculation:
read time/input, write output, change globals or variable arguments
expression evaluation can therefore alter observable state
2
side effect in the author's expression-focused terminology:
observable change occurring during evaluation, beyond its resulting value
examples: external variable changes and I/O
broader terminology also calls such effects in procedures side effects
3
NegotiateSize function example:
prompts until a positive odd height is entered
returns height
n := NegotiateSize div 2 embeds interactive I/O in an expression
4
make the action explicit with a procedure:
NegotiateSize(var res: integer) performs the same dialogue
NegotiateSize(n); n := n div 2
separates interaction from arithmetic in the caller
5
author's distinction concerns how actions are expressed:
ordinary assignment/I/O statements are explicit actions
his narrower use of side effect concerns actions hidden inside expressions
it does not mean a procedure performing I/O is pure
6
C/C++ make this distinction less syntactically visible:
assignment is an expression operation
their subprogram syntax does not provide Pascal's procedure category
7
course rule:
use expressions primarily to obtain values
consciously justified exceptions exist
learn to distinguish necessary effects from confusing hidden behavior
Recursion
A recursive subprogram calls itself. Every recursive solution
needs:
a base case that stops recursion
a smaller subproblem that moves toward the base case
Example:
function Fact(n: integer): integer;
begin
if n = 0 then
Fact := 1
else
Fact := n * Fact(n - 1);
end;
Recursion is natural for trees, lists, divide-and-conquer algorithms,
and backtracking.
Detailed notes - 2.3.7: Recursion
1
recursive call:
direct: a subprogram calls itself
indirect: a chain of calls returns to a subprogram already active
2
each invocation has its own locals:
allocated for the call, discarded when it returns
suspended callers keep their own values
3
termination needs:
a simpler instance at each recursive step
base case requiring no further recursive call
unbounded recursion consumes call storage and can exhaust it
4
recursive PrintChars:
count <= 0: do nothing
otherwise print one character, call PrintChars(ch, count-1)
count 3 produces calls for 3, 2, 1, 0, then returns through them
5
work during unwinding:
n mod 10 gives the last digit; n div 10 removes it
printing before recursion displays digits backward
recurse on n div 10 first, then print n mod 10 to restore normal order
zero requires an explicit wrapper case if it must print '0'
6
recursive functions can carry accumulated state:
ReverseNumber calls helper with remaining n and accumulator m = 0
step: (n div 10, m*10 + n mod 10)
base n = 0 returns m
752 -> 257; leading zeroes of the reversed numeral disappear
input/result must fit the intended nonnegative integer domain
This is enough for ordinary algorithms. It also keeps reasoning
local: the reader can understand one block at a time.
Detailed notes - 2.4: Constructing programs
1
small examples can conceal organizational problems:
a screenful of code is comparatively easy to hold in mind
2
larger programs exceed human working memory:
experience raises the limit but does not remove it
growing software complexity motivated disciplined program structure
Detailed notes - 2.4.1: Structured programming
1
unrestricted jumps entangle control flow:
difficult to reconstruct execution paths, even for the author
2
structured-programming foundations:
Dijkstra criticized uncontrolled goto use
Boehm-Jacopini: sequence, conditional selection, and iteration suffice
practical structured constructs have one entry and one exit
3
composition and abstraction:
refinement replaces one action by a detailed structured fragment
generalization treats such a fragment as one action
one entry/exit makes this substitution possible
4
top-down stepwise refinement:
begin with the main structure
use comments or skeletal subprograms for not-yet-implemented actions
replace them progressively, introducing finer subtasks as necessary
5
connection to flowcharts:
each temporary action represents a rectangle awaiting refinement
the earlier StarSlash example already used this approach
Exits From Loops and
Subprograms
Free Pascal provides controlled exits:
Statement
Effect
break
Leave the nearest loop
continue
Start the next loop iteration
exit
Leave the current procedure or function
Use these sparingly. They are useful when they remove awkward flags
or deeply nested conditions.
Detailed notes - 2.4.2: Early exits
1
clarity is the goal of structural rules:
a limited departure can be justified when it makes the program easier to understand
2
early-exit facilities:
end a subprogram, program, loop, or iteration
modern Pascal dialects provide specific constructs for these purposes
3
exit leaves the current subprogram:
handle n <= 0 in Fibonacci, set result, then exit
ordinary case follows without enclosing it in else
4
quadratic solver interface:
inputs a, b, c
outputs success flag and two real roots
repeated root can be returned twice
5
guard exceptional cases before normal work:
initialize ok := false
if a = 0 then exit
compute d := b*b-4*a*c; if d < 0 then exit
otherwise calculate roots and set ok := true
example deliberately rejects linear equations; only read roots when ok
6
guard clauses avoid increasing nesting:
normal case stays prominent
each rejected special case no longer needs to be considered afterward
7
halt terminates the whole program:
callable from inside subprograms
use deliberately; a recoverable user mistake should not automatically end everything
8
halt(status):
supplies process exit status
zero conventionally means success; nonzero indicates failure
Unix shell-visible status is normally limited to the low eight bits
9
bare halt:
the example treats it as a successful termination
explicit status communicates intent more clearly
10
loop exits:
break leaves the innermost loop
continue skips the remainder of its current iteration
useful where they simplify a more complex loop body
Goto
Pascal has labels and goto, but structured alternatives
are almost always better. goto destroys the usual block
structure and makes the path of control harder to inspect.
Detailed notes - 2.4.3: Unconditional jumps
1
goto label transfers control to a labeled statement:
labels can be identifiers or legacy numeric labels
meaningful names communicate their destination better
2
declare labels in a label section:
label Quit, AllDone, SecondStage;
keep labels local to the body where they are used
do not use jumps as substitutes for subprogram calls/returns
3
label syntax:
point: statement
goto point
author recommends restricting goto to two particular patterns
4
leave several nested constructs:
one forward jump can be clearer than flags checked throughout multiple loops
5
shared cleanup:
acquired resources must be released on every relevant exit path
early exits otherwise duplicate cleanup code
place a cleanup label near the end and jump to it when required
6
both recommended patterns jump forward and outward:
backward repetition belongs in a loop
jumping into the middle of a construct defeats its entry assumptions
Splitting Into Subprograms
Good reasons to create a subprogram:
the action has a clear name
the same logic appears more than once
a block is too large to understand at once
a piece can be tested independently
Avoid both extremes: one giant program and hundreds of tiny
meaningless wrappers.
Etude 2.14 prints a letter Z of stars with a given odd height. Each
subprogram has one job: ReadParams validates the argument,
PrintLineOfZ draws one row, and PrintChars
repeats a character.
Show the complete program
program test;
procedure PrintChars(c: char; n: integer);
var
i: integer;
begin
for i := 1 to n do
write(c);
end;
procedure PrintLineOfZ(i, n: integer);
var
m: integer;
begin
m := n div 2 + 1;
if (i = 1) or (i = m) or (i = n) then
PrintChars('*', n)
else
begin
PrintChars(' ', n - i);
PrintChars('*', 1);
end;
writeln()
end;
procedure CheckConvert(i, code: integer);
begin
if (code <> 0) then
begin
writeln('Could not convert ', i, ' parameter to number');
halt(2)
end;
end;
procedure ReadParams(var n: integer);
var
e: integer;
begin
if (ParamCount <> 1) then
begin
writeln('Wrong number of parameters, there have to be one of them');
halt(1)
end;
val(ParamStr(1), n, e);
CheckConvert(1, e);
if (n <= 5) or (n mod 2 = 0) then
begin
writeln('Please enter odd number that is larger than five');
halt(3)
end
end;
var
i, n: integer;
begin
ReadParams(n);
for i := 1 to n do
PrintLineOfZ(i, n);
end.
*******
*
*
*******
*
*
*******
Detailed notes - 2.4.4: Decomposing a program into subprograms
1
decomposition reduces the amount of detail considered at once
2
one growing main body or subprogram becomes difficult to
navigate/change:
small coherent subprograms can simplify even a longer overall source
3
complexity depends on simultaneous mental load:
understand one small implementation plus the overall call structure
other subprograms can be remembered by their contracts
4
author's size guideline:
aim for a body understandable at a glance, often around 25 source rows
longer case analysis can be reasonable
a growing body is a prompt to look for meaningful subtasks
5
historical basis of the guideline:
a conventional terminal displayed about 24/25 rows
fitting more text on a larger screen does not remove cognitive limits
6
one subprogram = one identifiable task:
split genuinely separable subtasks when they appear
7
false decomposition:
moving an arbitrary stretch of code into a new routine adds navigation
many shared variables/var parameters can preserve all the original coupling
8
finding boundaries requires practice:
two practical rules help test a proposed split
9
one-phrase rule:
describe the routine's purpose in one simple phrase
purpose plus parameter names should explain its inputs/outputs
10
keep interfaces manageable:
author recommends roughly five or fewer parameters as a heuristic
long parameter lists increase the effort and error risk of each call
11
independence rule:
caller should be understandable without callee's implementation
callee should be understandable without caller's implementation
constantly reading both bodies together indicates poor separation
12
optional reuse test:
imagine using the unchanged routine in a different program
plausible reuse is evidence of a coherent independent task
inability to reuse it alone does not prove the design bad
Characters and Text Data
Detailed notes - 2.5: Characters, character codes, and text
1
text representation:
sequences of character codes
encoding assigns numeric representations to characters
2
chapter's simplified model:
one byte per character; ASCII and byte-oriented extensions
some byte-stream transformations also work on UTF-8
general Unicode character processing needs more than this model
Characters and Codes
Values of type char represent characters. Characters are
ordinal values: they have codes and an order.
Useful operations:
Operation
Meaning
ord(c)
Character code
chr(n)
Character with code n
succ(c)
Next ordinal value
pred(c)
Previous ordinal value
Example:
if (c >= 'A') and (c <= 'Z') then
writeln('uppercase letter');
Detailed notes - 2.5.1: Character facilities in Pascal
1
char stores a single character/code unit in this model:
program PrintAscii;
var
i, j: integer;
c: char;
begin
write(' |');
for c := '0' to '9' do
write(' .', c);
for c := 'A' to 'F' do
write(' .', c);
writeln;
write(' |');
for i := 1 to 16 do
write('---');
writeln;
for i := 2 to 7 do
begin
write(i, '.|');
for j := 0 to 15 do
write(' ', chr(i * 16 + j));
writeln
end
end.
Character Input
Character-by-character input is useful for filters:
var
c: char;
begin
while not eof do begin
read(c);
write(c);
end;
end.
program ReadNumsByChar;
procedure ReadLongint(var success: boolean; var result: longint);
var
c: char;
res: longint;
pos: integer;
begin
res := 0;
pos := 0;
repeat
read(c);
pos := pos + 1
until (c <> ' ') and (c <> #10);
while (c <> ' ') and (c <> #10) do
begin
if (c < '0') or (c > '9') then
begin
writeln('Unexpected ``', c, ''''' in pos: ', pos);
readln;
success := false;
exit
end;
res := res*10 + ord(c) - ord('0');
read(c);
pos := pos + 1
end;
result := res;
success := true
end;
var
x, y: longint;
ok: boolean;
begin
repeat
write('Please type the first number: ');
ReadLongint(ok, x)
until ok;
repeat
write('Please type the second number: ');
ReadLongint(ok, y)
until ok;
writeln(x, ' times ', y, ' is ', x * y)
end.
Filters
A filter reads standard input, transforms it, and writes standard
output.
Filters should usually avoid prompts, because prompts become part of
the output stream.
Detailed notes - 2.5.3: Reading to EOF; filters
1
redirected input and pipes eventually run out of data
2
eof tests end-of-file state:
false: another character can be read
true: no more data available
no argument means standard input
3
EOF is a condition, not an ordinary character in the file:
regular-file length is tracked separately by the filesystem
4
no extra data byte must be read as an end marker:
eof asks about the stream's state
application formats can have sentinels, but those are a different concept
5
filter:
reads standard input and produces transformed/analyzed output
examples: grep, sort, cut, wc
stream interface makes filters composable in pipelines
6
FilterOk:
while not eof: read one character
on LF, print Ok
after the loop, print Good bye
counts line terminators; no whole-line storage needed
Ctrl-D at an empty terminal input line can signal EOF; Ctrl-C interrupts instead
7
line-length filter:
initialize count to zero
non-LF increments count
LF prints count and resets it
example handles newline-terminated lines; an unterminated final fragment needs extra handling
next example keeps/discards lines according to their first character
8
three logical states for line selection:
undecided, keep, discard
an enumeration would express them directly; example uses two booleans
9
on newline:
print it only if the current line was selected
reset know := false for the next line
10
on the first non-newline character:
print := (c <> ' ') and (c <> #9)
set know := true
11
after classification:
print the character only if print is true
remaining characters use the existing decision
12
initial state and self-test:
know := false; print := false
feeding the program its source retains only unindented nonempty lines
13
terminal buffering:
normal terminal mode supplies completed input lines
character-by-character processing does not imply one-keystroke-at-a-time interaction
14
storage needs depend on the task:
some filters need only a few state variables
others need complete lines or much larger datasets
sorting can also use external storage when data exceeds memory
This matches Unix pipelines well:
producer | filter | consumer
Book examples (3 files) - 2.5.3: Reading to EOF; filters
Book exampleBook example: filter_len.pasIn catalog
program FilterLength;
var
c: char;
n: integer;
begin
n := 0;
while not eof do
begin
read(c);
if c = #10 then
begin
writeln(n);
n := 0
end
else
n := n + 1
end
end.
program SkipIndented;
var
c: char;
know, print: boolean;
begin
know := false;
print := false;
while not eof do
begin
read(c);
if c = #10 then
begin
if know and print then
writeln;
know := false
end
else
begin
if not know then
begin
print := (c <> ' ') and (c <> #9);
know := true
end;
if print then
write(c)
end
end
end.
Reading Numbers Until EOF
For numeric streams:
var
x, sum: longint;
begin
sum := 0;
while not eof do begin
read(x);
sum := sum + x;
end;
writeln(sum);
end.
This pattern works well with files and pipelines.
Detailed notes - 2.5.4: Reading numbers to EOF
1
character EOF loop cannot be copied blindly for numeric input
2
example task:
count and sum all input integers
input length unknown; EOF ends it
chosen numeric types must accommodate values and their sum
3
naive pattern:
while not eof do read(n), add n, increment count
may attempt an extra numeric read after the final actual number
4
numeric reading has several stages:
skip leading separators
parse the number's characters
stop when the representation ends
5
trailing whitespace explains the problem:
after the last number, newline/spaces may still remain
eof is false although no further number exists
the book's runtime example then counts a spurious zero
do not equate remaining characters with a valid next number
6
terminal EOF can be transient:
later reads may accept more terminal input
this differs from repeatedly reading an exhausted ordinary file
7
SeekEof:
skips whitespace before testing for exhaustion
leaves the next nonwhitespace character available to read
8
use while not SeekEof for whitespace-separated numbers:
then read, accumulate, and count
malformed numeric tokens still require separate error handling
9
historical Free Pascal problem described by the author:
older SeekEof implementations failed on streams such as pipes
10
author's account of its origin:
behavior was documented as a limitation rather than promptly corrected
11
2020 investigation:
author compared the intended semantics and historical Borland implementation
emphasizes testing stream behavior, not only disk-file behavior
12
reported follow-up regression:
author says related output buffering changed during the fix
13
version context in the book:
corrected SeekEof included in Free Pascal 3.2.2, released in 2021
recommendations about available distribution versions reflect the book's date
14
author's conclusion about tool choice:
this experience reduced his confidence in Free Pascal for professional work
it remains his teaching implementation
15
SeekEoln:
skips horizontal whitespace while testing for end of the current line
useful for variable-length groups of numbers separated by line boundaries
Pascal Type System
Book examples (2 files) - 2.6: Pascal's type system
program OlympiadCounter;
const
MaxSchool = 67;
MaxGroup = 100;
type
CountersArray = array [1..MaxSchool] of integer;
var
Counters: CountersArray;
i, c, n: integer;
begin
for i := 1 to MaxSchool do
Counters[i] := 0;
{$I-}
while not eof do
begin
readln(c);
if IOResult <> 0 then
begin
writeln('Incorrect data');
halt(1)
end;
n := c div MaxGroup;
if (n < 1) or (n > MaxSchool) then
begin
writeln('Illegal school id: ', n, ' [', c, ']');
halt(1)
end;
Counters[n] := Counters[n] + 1
end;
n := 1;
for i := 2 to MaxSchool do
if Counters[i] > Counters[n] then
n := i;
for i := 1 to MaxSchool do
if Counters[i] = Counters[n] then
writeln(i)
end.
Built-In and User Types
Pascal lets the programmer define new names for types:
type
Count = longint;
Index = 1..100;
Types document intent and help the compiler detect mistakes.
Detailed notes - 2.6.1: Built-in and user-defined types
1
built-in types:
compiler already knows integer, real, boolean, and similar types
2
user-defined types:
programmer introduces a type, usually with a name
unnamed types are called anonymous
user here means the compiler's user: the programmer
3
type declaration section:
starts with type
may be global or local to a subprogram
scope follows the same broad rules as other declarations
4
type alias:
type MyNumber = real;
new name for the existing type, compatible with it
changing representations separately throughout a large program is error-prone
5
choosing the widest type for everything has costs:
may still be insufficient later
wastes storage in large structures and can affect performance
6
name a type by its role:
type SimObjectId = integer;
use SimObjectId wherever an object's identifier is required
change its definition once if the identifier range must grow
Subranges and Enumerations
Subrange type:
type
MonthNumber = 1..12;
Enumeration type:
type
Color = (Red, Green, Blue);
These are ordinal types: their values have an order and can be used
in for loops, arrays, and case statements.
Detailed notes - 2.6.2: Subranges and enumerations
1
aliases add names; subranges/enumerations introduce more specific types
2
subrange:
type digit10 = 0..9;
restricts values to that interval
enable appropriate range checks when run-time validation is needed
3
subrange representation:
Free Pascal normally uses an integer representation able to hold its bounds
15000..15010 does not become an offset encoded in a single byte
direct representation avoids extra conversion during arithmetic
4
other ordinal subranges:
LatinCaps = 'A'..'Z'
boundaries must be compile-time constants
5
enumeration:
names its possible values explicitly in declaration order
do not step before the first or after the last value
6
pred/succ also apply to other ordinal types
7
ord gives an enumeration value's ordinal:
ordinary enumeration starts at zero and advances by one
8
explicit-number enumeration extensions:
dialects can permit them, with additional restrictions
author excludes these extensions from the teaching subset
9
value names must not conflict in the same scope:
red in both RainbowColors and Signals is ambiguous in the ordinary model
prefixes such as RcRed and SigRed distinguish the meanings
Ordinal Types
Ordinal types include integer types, char,
boolean, enumerations, and subranges.
Useful operations:
Operation
Meaning
ord(x)
Numeric position
succ(x)
Next value
pred(x)
Previous value
low(T)
Lowest value of type T
high(T)
Highest value of type T
Do not call succ on the last value or pred
on the first value.
Enumeration values are ordinal, but they are not numbers. Arithmetic
on them does not compile; ord(rc1) * ord(rc2) would
multiply their positions instead:
program types;
type
RainbowColors =
(red, orange, yellow, green, blue, indigo, violet);
var
rc1, rc2, rc3: RainbowColors;
begin
rc1 := green;
rc2 := yellow;
rc3 := rc1 * rc2; { error: no * for an enumeration }
writeln(rc3);
end.
Detailed notes - 2.6.3: Ordinal types
1
ordinal type has:
ordered values with integer ordinal numbers
minimum and maximum
successor/predecessor except at the respective endpoint
ord, succ, pred expose these relationships
2
examples:
boolean: false then true
char: ordered by codes
integer types, enumerations, and ordinal subranges
floating-point types do not support this Pascal ordinal interface
restrictions on particular constructs/types depend on the dialect
3
ordinal types form a useful language category:
subrange definitions and several later constructs require an ordinal type
an arbitrary real interval cannot be substituted for one
program SymbolType;
var
c: char;
begin
read(c);
write('The symbol is ');
case c of
'a'..'z', 'A'..'Z':
writeln('a latin letter');
'0'..'9':
writeln('a digit');
'+', '-', '/', '*':
writeln('an arithmetic operation symbol');
'<', '>', '=':
writeln('a comparision sign');
'.', ',', ';', ':', '!', '?':
writeln('a punctuation symbol');
'_', '~', '@', '#', '$', '%', '^',
'&', '`', '|', '\':
writeln('a special purpose sign');
' ':
writeln('the space character');
#9, #10, #13:
writeln('a formatting code');
#27:
writeln('the escape code');
'(', ')', '[', ']', '{', '}':
writeln('a grouping symbol');
'"', '''':
writeln('a quoting symbol');
else
writeln('something strange')
end
end.
Full-Screen Programs
Free Pascal can use the crt unit for terminal-style
full-screen interaction:
uses crt;
begin
clrscr;
gotoxy(10, 5);
textcolor(lightgreen);
writeln('Hello');
end.
Common crt tools:
Tool
Meaning
clrscr
Clear screen
gotoxy(x, y)
Move cursor
whereX, whereY
Current cursor position
keypressed
Whether a key is waiting
readkey
Read one key
textcolor, textbackground
Change colors
delay(ms)
Pause
Dynamic input reads keys as events rather than waiting for a whole
line. This is useful for simple games and interactive demos, but
terminal behavior can depend on the environment.
Detailed notes - 2.8: Full-screen programs
1
optional practical detour:
these terminal facilities are not prerequisites for later chapters
2
self-chosen projects matter:
more available techniques make personally interesting projects possible
3
full-screen text interfaces:
use terminal positions and immediate key input
go beyond ordinary line-oriented dialogue
4
text interfaces can support substantial applications:
editors, mail/chat clients, and games such as NetHack
5
dynamic terminal games are one possible application
usefulness is broader than games
6
reading strategy:
skip if already working on an interesting project that does not need these tools
program ColorsDemo;
uses crt;
const
ColorCount = 16;
BGColCount = 8;
var
AllColors: array [1..ColorCount] of word =
(
Black, Blue, Green, Cyan,
Red, Magenta, Brown, LightGray,
DarkGray, LightBlue, LightGreen, LightCyan,
LightRed, LightMagenta, Yellow, White
);
procedure MakeLine(line: integer; fgcolor: word);
var
i, w, cw: integer;
begin
w := ScreenWidth;
cw := w div BGColCount;
if cw = 0 then
cw := 1;
if line = ScreenHeight then
w := w - 1;
for i := 1 to w do
begin
GotoXY(i, line);
TextBackground(AllColors[(i-1) div cw + 1]);
if i mod 2 = 0 then
TextColor(fgcolor + blink)
else
TextColor(fgcolor);
write('*')
end
end;
procedure MakeScreen;
var
i: integer;
begin
clrscr;
for i := 1 to ScreenHeight do
MakeLine(i, AllColors[i mod ColorCount + 1])
end;
var
SaveTextAttr: integer;
begin
SaveTextAttr := TextAttr;
MakeScreen;
readln;
{write(#27'[0m');}
TextAttr := SaveTextAttr;
clrscr
end.
Detailed notes - 2.8.1: Background
1
escape sequences control terminals:
byte sequences commonly beginning with ESC, code 27
move cursor, set attributes, scroll, and perform other screen actions
2
full-screen input also needs terminal-mode changes:
canonical mode delivers completed lines
Ctrl-C/Ctrl-D normally receive special driver treatment
applications can configure these behaviors
3
terminal differences motivate libraries:
libraries hide differing control sequences/capabilities
ncurses is a common C example
4
crt history:
originated in Borland Pascal's DOS environment
Free Pascal implements a compatible interface using host-system facilities
5
crt is the simpler interface chosen for these teaching examples
6
import it with uses crt:
placed after the program header
startup changes terminal behavior
provide an explicit way to exit; familiar interrupt keys may behave differently
7
crt assumes an interactive terminal:
do not treat these examples as ordinary redirectable stream filters
Detailed notes - 2.8.2: Output at arbitrary screen positions
1
clrscr:
clears the screen and moves cursor to the upper-left corner
2
GotoXY(x, y):
horizontal position first, vertical position second
upper-left cell is (1,1)
ScreenWidth / ScreenHeight provide terminal dimensions known to crt
program GtKey;
uses crt;
procedure GetKey(var code: integer);
var
c: char;
begin
c := ReadKey;
if c = #0 then
begin
c := ReadKey;
code := -ord(c)
end
else
begin
code := ord(c)
end
end;
var
i: integer;
begin
repeat
GetKey(i);
writeln(i)
until i = ord(' ')
end.
program MovingHello;
uses crt;
const
KeyLeft = -75;
KeyRight = -77;
KeyUp = -72;
KeyDown = -80;
TheMessage = 'Hello, world!';
procedure GetKey(var code: integer);
var
c: char;
begin
c := ReadKey;
if c = #0 then
begin
c := ReadKey;
code := -ord(c)
end
else
begin
code := ord(c)
end
end;
procedure ShowMessage(x, y: integer; msg: string);
begin
GotoXY(x, y);
write(msg);
GotoXY(1, 1)
end;
procedure HideMessage(x, y: integer; msg: string);
var
len, i: integer;
begin
len := length(msg);
GotoXY(x, y);
for i := 1 to len do
write(' ');
GotoXY(1, 1)
end;
procedure MoveMessage(var x, y: integer; msg: string; dx, dy: integer);
begin
HideMessage(x, y, msg);
x := x + dx;
y := y + dy;
ShowMessage(x, y, msg)
end;
var
CurX, CurY: integer;
c: integer;
begin
clrscr;
CurX := (ScreenWidth - length(TheMessage)) div 2;
CurY := ScreenHeight div 2;
ShowMessage(CurX, CurY, TheMessage);
while true do
begin
GetKey(c);
if c > 0 then { non-extended code; quit }
break;
case c of
KeyLeft:
MoveMessage(CurX, CurY, TheMessage, -1, 0);
KeyRight:
MoveMessage(CurX, CurY, TheMessage, 1, 0);
KeyUp:
MoveMessage(CurX, CurY, TheMessage, 0, -1);
KeyDown:
MoveMessage(CurX, CurY, TheMessage, 0, 1)
end
end;
clrscr
end.
Book exampleBook example: movingstar.pasIn catalog
program RdKey;
uses crt;
var
c, cc: char;
begin
repeat
c := ReadKey;
cc := c;
if (cc < #32) or (cc > #126) then
cc := '?';
writeln(ord(c), ' (', cc, ')')
until c = ' '
end.
Detailed notes - 2.8.4: Color control
1
terminals can choose foreground and background colors
2
crt exposes a historically limited attribute model:
sixteen foreground colors, eight background colors, blink flag
inherited from the DOS text-screen interface
3
compatibility explains the limits:
other interfaces can expose wider terminal capabilities
author keeps crt here because it is easy to learn
4
TextColor / TextBackground:
named color constants select subsequent output attributes
TextColor(Yellow); TextBackground(Blue) gives yellow text on blue
TextColor(Blue or Blink) requests blinking blue text where supported
5
restore attributes before exit:
save TextAttr before changing colors
restore it at the end, then perform output such as clrscr to apply it
program RandomStars;
uses crt;
const
DelayDuration = 20;
ColorCount = 16;
var
AllColors: array [1..ColorCount] of word =
(
Black, Blue, Green, Cyan,
Red, Magenta, Brown, LightGray,
DarkGray, LightBlue, LightGreen, LightCyan,
LightRed, LightMagenta, Yellow, White
);
var
x, y, col: integer;
SaveTextAttr: integer;
begin
randomize;
SaveTextAttr := TextAttr;
clrscr;
while not KeyPressed do
begin
x := random(ScreenWidth) + 1;
y := random(ScreenHeight) + 1;
if (x = ScreenWidth) and (y = ScreenHeight) then
continue;
col := random(ColorCount) + 1;
GotoXY(x, y);
TextColor(AllColors[col]);
write('*');
delay(DelayDuration)
end;
TextAttr := SaveTextAttr;
clrscr
end.
Files
General Pattern
A file variable connects program code to an external file:
var
f: text;
begin
assign(f, 'data.txt');
reset(f); { open existing file for reading }
{ read from f }
close(f);
end.
Opening modes:
Procedure
Meaning
reset(f)
Open existing file for reading
rewrite(f)
Create/truncate file for writing
append(f)
Open text file for appending
close(f)
Finish work with the file
Detailed notes - 2.9.1: General principles
1
programs can open files themselves:
not limited to streams arranged by shell redirection
operating-system permissions still apply
2
opening a file:
identify its path and intended access mode
obtain an associated stream for subsequent operations
3
file variables identify active streams:
special types with restricted operations
no ordinary assignment or independent file-value expressions
pass file variables through var parameters
4
three interfaces:
text: textual input/output
file: untyped block I/O
file of T: fixed-size values represented as T
selected interface reflects the operation the program needs
5
assign(f, filename):
associates a path with a file variable
does not open/create the file or check existence
filename may be calculated at run time
Unix leading / means absolute path; otherwise relative to current directory
6
filename belongs to the filesystem:
program may obtain it from arguments, input, or another file
7
file-variable name belongs to source code:
arbitrary identifier, independent of disk filename
8
assign establishes the association:
a closed file variable can later be assigned another path
9
opening operations:
reset: open existing file from its beginning
rewrite: create or truncate to an empty file
append: open text output at its end
actual read/write access for typed/untyped files also depends on FileMode
10
expect opening failures:
handle I/O status explicitly with {$I-} and IOResult when useful
report errors in terms meaningful to the user
11
read/write with a file variable first:
read(f, x), write(f, x)
text interface converts to/from textual representation
typed-file interface transfers a fixed-size value representation
readln/writeln apply to text; eof(f) tests a specified stream
12
untyped files use BlockRead / BlockWrite
13
close(f) ends work with the open stream:
afterward f may be reopened for the same path or assigned a different one
14
HelloFile example:
assign, rewrite, writeln(f, message), close
Unix output contains greeting plus newline
check opening, writing, and final close/flush failures when correctness matters
successful open does not guarantee successful later writes
15
current position:
ordinary reading/writing advances it by transferred data
program GenerateNumTxt;
const
name = 'numbers.txt';
start = 1000;
step = 1001;
count = 100;
var
f: text;
i: integer;
n: longint;
begin
assign(f, name);
rewrite(f);
n := start;
for i := 1 to count do
begin
writeln(f, n);
n := n + step
end;
close(f)
end.
Book exampleBook example: multandadd.pasIn catalog
program MultAndAdd;
var
sum, mul, n: real;
f: text;
begin
{$I-}
if ParamCount < 1 then
begin
writeln('Please specify the file name');
halt
end;
assign(f, ParamStr(1));
reset(f);
if IOResult <> 0 then
begin
writeln('Could not open ', ParamStr(1));
halt
end;
sum := 0;
while not SeekEof(f) do
begin
mul := 1;
while not SeekEoln(f) do
begin
read(f, n);
mul := mul * n
end;
readln(f);
sum := sum + mul
end;
close(f);
writeln(sum:7:5)
end.
Typed Files
A typed file stores values of one Pascal type:
type
Item = record
key: longint;
value: longint;
end;
var
f: file of Item;
Typed files are compact and easy for Pascal programs to read, but
they are not good interchange formats unless the exact layout is
controlled.
Detailed notes - 2.9.3: Typed files
1
typed file = sequence of fixed-size representations:
file of longint stores longint values directly
same generating loop as text example, but write replaces writeln
representation depends on type/compiler/platform; it is not a portable text encoding
2
element-type restrictions:
file variables cannot be stored as file elements
pointer values generally have no useful persistent meaning in another execution
file of char can access a byte-oriented file one element at a time
3
record elements:
NamedPoint combines coordinates and a bounded name
file of NamedPoint stores a sequence of those records
rewrite creates/truncates; reset opens existing data
4
seek(f, index) selects a zero-based record position:
fixed size makes direct positioning possible
to change record 705: seek, read, alter field, seek back, write
second seek is necessary because read advanced to record 706
5
positioning requires a seekable stream:
regular files support it
terminal/pipe streams do not provide ordinary random-access file semantics
6
default typed-file access in the described runtime:
reset normally requests reading and writing
rewrite creates/truncates, while reset preserves existing contents
7
FileMode controls reset's access mode:
0: read only; 1: write only; 2: read/write
select read-only mode when only reading is needed
write-only reset still preserves previous contents
FileMode does not give rewrite the same mode behavior
program GenerateNumBin;
const
name = 'numbers.bin';
start = 1000;
step = 1001;
count = 100;
var
f: file of longint;
i: integer;
n: longint;
begin
assign(f, name);
rewrite(f);
n := start;
for i := 1 to count do
begin
write(f, n);
n := n + step
end;
close(f)
end.
Untyped Files and Block I/O
Untyped files are used for byte/block operations:
var
f: file;
Use blockread and blockwrite when the
program needs raw binary transfer.
Detailed notes - 2.9.4: Block I/O
1
untyped files transfer arbitrary chunks:
practical interface close to operating-system byte/block I/O
2
transfer data between file and memory buffer:
opening specifies block size
each transfer specifies a number of blocks
block size 1 makes those counts byte counts
3
declare f: file:
assign as usual
reset(f, 1) or rewrite(f, 1) explicitly chooses one-byte blocks
omitted block size defaults to 128 in the discussed interface
4
opening modes:
FileMode affects reset as with typed files
5
BlockRead / BlockWrite arguments:
file variable
buffer variable
requested block count
variable receiving actual transferred count
block_count * block_size must fit the buffer
short read may simply mean fewer bytes remain
zero bytes read without an I/O error indicates EOF
6
keep the actual-count result:
omitting it can turn ordinary short reads into runtime errors
check I/O status as well when an actual error must be distinguished from EOF
7
copy-file example:
source/destination paths come from arguments
source opened read-only; destination created/truncated
transfer buffer = 4096 bytes; block size = one byte
8
copy loop:
read a chunk and inspect actual count/status
stop at EOF before attempting a write
write exactly the bytes read, including a partial final chunk
compare actual written count with actual read count
close both files; send diagnostics to ErrOutput
sample's write-error branch only breaks; a complete version must also return failure
read and final close errors also require checks for reliable copying
program BlockFileCopy;
const
BufSize = 4096;
var
src, dest: file;
buffer: array [1..BufSize] of byte;
ReadRes, WriteRes: longint;
begin
{$I-}
if ParamCount < 2 then
begin
writeln(ErrOutput, 'Expected: source and dest. names');
halt(1)
end;
assign(src, ParamStr(1));
assign(dest, ParamStr(2));
filemode := 0;
reset(src, 1); { block size of 1 byte }
if IOResult <> 0 then
begin
writeln(ErrOutput, 'Couldn''t open ', ParamStr(1));
halt(1)
end;
rewrite(dest, 1);
if IOResult <> 0 then
begin
writeln(ErrOutput, 'Couldn''t open ', ParamStr(2));
halt(1)
end;
while true do
begin
BlockRead(src, buffer, BufSize, ReadRes);
if ReadRes = 0 then { end of file! }
break;
BlockWrite(dest, buffer, ReadRes, WriteRes);
if WriteRes <> ReadRes then
begin
writeln(ErrOutput, 'Error writing the file');
break
end
end;
close(src);
close(dest)
end.
File Operations
Free Pascal provides operations on whole files:
Procedure
Meaning
erase(f)
Delete file assigned to f
rename(f, newname)
Rename file assigned to f
Always check errors in serious programs. Silent file failures are
hard to debug.
Detailed notes - 2.9.5: Operations on whole files
1
whole-file operations:
erase deletes a file
rename changes its filesystem name
2
use an assigned, closed file variable:
assign(f, path) before erase(f)
assign(f, old_path) before rename(f, new_path)
any of the file-variable categories can be used
if it was open, close it first
examples validate command-line arguments and check IOResult
report failure through ErrOutput and a nonzero exit status
Book example (1 file) - 2.9.5: Operations on whole files
program EraseFile;
var
f: file;
begin
{$I-}
if ParamCount < 1 then
begin
writeln(ErrOutput, 'Please specify the file to erase');
halt(1)
end;
assign(f, ParamStr(1));
erase(f);
if IOResult <> 0 then
begin
writeln(ErrOutput, 'Error erasing the file');
halt(1)
end
end.
Addresses, Pointers, and
Dynamic Memory
Detailed notes - 2.10: Addresses, pointers, and dynamic memory
1
variables declared in the program:
their types and sizes determine memory requirements before execution
2
memory requirements may depend on the input:
fixed teaching limits do not necessarily suit real tasks
sort accepts arbitrary line lengths and counts, within available resources
allocate the memory needed by the particular input
3
dynamic variables:
created during execution; accessed through addresses and pointers
let the program determine its memory needs at runtime
pointers also have uses beyond dynamic allocation
4
pointers may take considerable effort to understand
5
preparation for C:
Pascal permits substantial programming before introducing pointers
C requires a clear understanding of addresses from an early stage
6
do not leave pointers unresolved before proceeding:
seek help, practise with familiar tools, or study the assembly material
return after gaining experience if necessary
Pointers
A pointer stores an address. nil means "points
nowhere".
Typed pointer:
type
PInteger = ^integer;
var
p: PInteger;
p^ means the object pointed to by p.
Detailed notes - 2.10.1: What a pointer is
1
address:
information uniquely identifying a memory cell
often an integer; some architectures use more complex representations
2
memory region:
consecutive cells; a variable occupies such a region
address of the region = address of its first cell
3
pointer:
a variable containing an address
one region of memory can contain the address of another
4
A points to B = A contains B's address
pointer: variable; address: value stored in it
informal expressions such as 'return a pointer' usually mean return an address
Detailed notes - 2.10.2: Pointers in Pascal
1
typed pointers:
pointed-to type tells the compiler how to interpret the addressed region
p: ^integer; q: ^real
^ replaces the upward arrow used in Wirth's original notation
2
address-of operation: @x
p := @r makes p contain r's address
applies to any variable, including array elements and record fields
3
original Pascal lacked address-of:
pointer use was largely restricted to dynamic variables
the dialect used here supplies @
4
dereference: p^
denotes the variable at the address contained in p
after p := @r, p^ and r denote the same variable
p^ := 25.7 changes r; writeln(p^) prints its value
5
untyped pointer: pointer
can hold an address without specifying the stored value's type
assignments to typed pointers can bypass useful type checks
interpreting a string's address as ^integer does not make an integer exist there
6
@ produces an untyped address by default in the dialect discussed
{$T+} enables typed addresses
7
nil:
special invalid address; indicates that a pointer currently points nowhere
often called a null pointer, although nil itself is a value
8
pointer notation:
^t: pointer-to-t type
@x: address of x
p^: variable reached through p
nil: no addressed variable
Dynamic Variables
Dynamic variables are created on the heap:
new(p);
p^ := 42;
writeln(p^);
dispose(p);
p := nil;
Pascal does not normally provide garbage collection. Every successful
new must eventually be matched by dispose when
the object is no longer needed.
Detailed notes - 2.10.3: Dynamic variables
1
dynamic variable:
memory region created during execution
has no identifier of its own; accessed through an address
2
heap:
supplies storage for dynamic variables
disposing of a variable makes its region available for reuse
the allocation model described retains acquired heap memory until exit
freeing obsolete storage before allocating replacements can reduce peak use
3
new(p):
requires a typed pointer
allocates enough storage for the pointed-to type
stores the new region's address in p
4
p: ^string; new(p)
creates a string variable in the heap
the short-string representation used here occupies 256 bytes
p^ := 'This is a string, which resides in the heap' fills it
5
dispose(p):
releases the variable addressed by p
does not change p itself
p still contains the old address, which must no longer be dereferenced
6
allocation belongs to an address, not to one particular pointer:
q := p copies the address; p^ and q^ denote the same variable
p can subsequently be reused while q retains access
dispose(q) releases that same allocation
7
losing the only address:
a second new(p) overwrites p without disposing of its previous allocation
the first variable remains allocated but can no longer be reached
8
garbage:
unreachable allocated memory
distinct from junk: meaningless/uninitialized data
some languages reclaim garbage automatically; collection can pause execution
9
memory leak:
allocated storage is lost without being released
this Pascal model has no automatic garbage collection
retain ownership information and dispose of unneeded variables
10
why use dynamic storage:
large temporary objects can exceed practical stack limits
allocate and release objects according to when they are needed
the main applications here are linked structures built from records containing pointers
Linked Lists
A node usually contains data and a pointer to the next node:
type
PNode = ^Node;
Node = record
value: integer;
next: PNode;
end;
The type PNode is declared before Node is
fully known. Pascal allows this special forward reference for pointer
types, which is essential for recursive data structures.
Basic list operations:
create an empty list: head := nil
insert at the beginning
scan with a pointer variable
delete by rewiring links
dispose removed nodes
Sorted insertion needs no special case for the head of the list.
p is a variable parameter, so push can change
either the head pointer or the next field of the previous
node:
procedure insert(var p: itemptr; n: integer);
begin
if (p = nil) or (n < p^.data) then
push(p, n)
else
insert(p^.next, n)
end;
Show the complete program
program list;
type
itemptr = ^item;
item = record
data: integer;
next: itemptr;
end;
procedure init(var p: itemptr);
begin
p := nil;
end;
procedure print(p: itemptr); { a copy: the caller keeps its list }
begin
while (p <> nil) do
begin
write(p^.data, ' ');
p := p^.next
end;
writeln()
end;
procedure push(var p: itemptr; n: integer);
var
tmp: itemptr;
begin
new(tmp);
tmp^.data := n;
tmp^.next := p;
p := tmp;
end;
procedure insert(var p: itemptr; n: integer);
begin
if (p = nil) or (n < p^.data) then
push(p, n)
else
insert(p^.next, n)
end;
var
i: integer;
a: array [1..4] of integer = (1, 3, 6, 9);
p: itemptr;
begin
init(p);
for i := 4 downto 1 do
push(p, a[i]);
insert(p, 4);
print(p);
end.
1 3 4 6 9
Detailed notes - 2.10.4: Singly linked lists
1
singly linked list:
each node contains data and a pointer to the next node
last node's next = nil
a pointer to the first node makes the whole chain reachable
2
one chain of links:
one next field per node
each node is reached through the preceding link or the head pointer
3
node type for integer data:
data: integer; next: pointer to the same record type
naming the record inside its own declaration is restricted in older Pascal implementations
4
forward pointer type:
declare itemptr = ^item before declaring item
item contains data: integer and next: itemptr
first^ = first record; first^.next = pointer to the second
first^.next^ = second record; first^.next^.data = its value
explicit new calls can build 25 -> 36 -> 49 -> nil
5
understand each dereference and field selection before continuing
6
usual construction methods:
prepend through a temporary pointer
or maintain first and last, and append
try implementing the exercises before reading the solutions
7
exercises:
read integers to EOF and print them in reverse order
read integers to EOF and print them twice in their original order
no fixed limit on the number of integers
a working, tested program is required; an imagined solution is insufficient
8
initialize an empty list: first := nil
an uninitialized pointer does not represent a valid empty list
9
prepend in three stages:
allocate a node through tmp
set its data and make tmp^.next point to the old first node
assign first := tmp
10
prepending 25 to 36 -> 49:
new(tmp)
tmp^.data := 25; tmp^.next := first
first := tmp
allocation alone leaves the original list unchanged and the new fields uninitialized
11
empty-list case needs no separate prepend algorithm:
the old first is nil, so the new node's next becomes nil
requires correct initial first := nil
12
reverse-order program:
read with while not SeekEof; prepend each value
traverse from first while tmp <> nil; print tmp^.data; advance tmp := tmp^.next
list disposal:
save first^.next, dispose(first), then replace first with the saved address
or save first, advance first, then dispose the saved node
never read a node's next after disposing of that node
exit releases the example's storage; repeated work in a longer program needs explicit disposal
13
preserve input order by appending:
reversing an already built list is possible, but unnecessary here
14
append with first and last:
empty list: both nil; allocate first and assign last := first
nonempty list: new(last^.next); last := last^.next
fill last^.data and set last^.next := nil
alternative using tmp:
allocate and fill tmp, with tmp^.next := nil
if empty, first := tmp; otherwise last^.next := tmp
finish with last := tmp
draw and check both the empty and nonempty cases
15
complete the second exercise independently:
append during input, then traverse the completed list twice
program QOLDemo;
type
LongItemPtr = ^LongItem;
LongItem = record
data: longint;
next: LongItemPtr;
end;
type
QueueOfLongints = record
first, last: LongItemPtr;
end;
procedure QOLInit(var queue: QueueOfLongints);
begin
queue.first := nil;
queue.last := nil
end;
procedure QOLPut(var queue: QueueOfLongints; n: longint);
begin
if queue.first = nil then
begin
new(queue.first);
queue.last := queue.first
end
else
begin
new(queue.last^.next);
queue.last := queue.last^.next
end;
queue.last^.data := n;
queue.last^.next := nil
end;
procedure QOLGet(var queue: QueueOfLongints; var n: longint);
var
tmp: LongItemPtr;
begin
n := queue.first^.data;
tmp := queue.first;
queue.first := queue.first^.next;
if queue.first = nil then
queue.last := nil;
dispose(tmp)
end;
function QOLIsEmpty(var queue: QueueOfLongints) : boolean;
begin
QOLIsEmpty := queue.first = nil
end;
var
s: QueueOfLongints;
n: longint;
begin
QOLInit(s);
while not eof do
begin
readln(n);
QOLPut(s, n)
end;
while not QOLIsEmpty(s) do
begin
QOLGet(s, n);
writeln(n)
end
end.
program SOLDemo;
type
LongItemPtr = ^LongItem;
LongItem = record
data: longint;
next: LongItemPtr;
end;
type
StackOfLongints = LongItemPtr;
procedure SOLInit(var stack: StackOfLongints);
begin
stack := nil
end;
procedure SOLPush(var stack: StackOfLongints; n: longint);
var
tmp: LongItemPtr;
begin
new(tmp);
tmp^.data := n;
tmp^.next := stack;
stack := tmp
end;
procedure SOLPop(var stack: StackOfLongints; var n: longint);
var
tmp: LongItemPtr;
begin
n := stack^.data;
tmp := stack;
stack := stack^.next;
dispose(tmp)
end;
function SOLIsEmpty(var stack: StackOfLongints) : boolean;
begin
SOLIsEmpty := stack = nil
end;
var
s: StackOfLongints;
n: longint;
begin
SOLInit(s);
while not eof do
begin
readln(n);
SOLPush(s, n)
end;
while not SOLIsEmpty(s) do
begin
SOLPop(s, n);
writeln(n)
end
end.
program list;
type
itemptr = ^item;
item = record
data: integer;
next: itemptr;
end;
procedure init(var p: itemptr);
begin
p := nil;
end;
procedure print(var p: itemptr);
begin
while (p <> nil) do
begin
write(p^.data, ' ');
p := p^.next
end;
writeln()
end;
procedure push(var p: itemptr; n: integer);
var
tmp: itemptr;
begin
new(tmp);
tmp^.data := n;
tmp^.next := p;
p := tmp;
end;
procedure insert(var p: itemptr; n: integer);
begin
if (p = nil) or (n < p^.data) then
push(p, n)
else
insert(p^.next, n)
end;
var
i: integer;
a: array [1..4] of integer = (1, 3, 6, 9);
p: itemptr;
begin
init(p);
for i := 4 downto 1 do
push(p, a[i]);
insert(p, 4);
print(p);
end.
Stack and Queue
A stack is LIFO: last in, first out. With a linked list, push and pop
are operations at the head.
A queue is FIFO: first in, first out. It usually keeps both head and
tail pointers.
Etude 2.42 prints the words of each input line in reverse order,
without the string type and without limits on lengths. Each
word is a queue of characters, appended at its tail; the words of a line
form a stack, so they come out reversed:
type
pwt = ^wt;
wt = record
c: char;
n: pwt
end;
pwts = record
b: pwt;
e: pwt
end;
pst = ^st;
st = record
w: pwts;
n: pst;
end;
procedure AppendStr(w: pwts; var s: pst);
var
t: pst;
begin
new(t);
t^.w := w;
t^.n := s;
s := t;
end;
Show the complete program
program ptrnum;
type
pwt = ^wt;
wt = record
c: char;
n: pwt
end;
pwts = record
b: pwt;
e: pwt
end;
pst = ^st;
st = record
w: pwts;
n: pst;
end;
procedure InitWord(var w: pwts);
begin
w.b := nil;
w.e := nil
end;
procedure InitStr(var s: pst);
begin
s := nil
end;
procedure AppendChar(c: char; var w: pwts);
var
t: pwt;
begin
new(t);
t^.c := c;
t^.n := nil;
if (w.b = nil) then
begin
w.b := t;
w.e := w.b
end
else
begin
w.e^.n := t;
w.e := w.e^.n
end
end;
procedure AppendStr(w: pwts; var s: pst);
var
t: pst;
begin
new(t);
t^.w := w;
t^.n := s;
s := t;
end;
procedure ReadWord(var w: pwts; var next: boolean);
var
c: char;
begin
while true do
begin
read(c);
if (c = ' ') or (c = #9) then
exit
else if (c = #10) then
begin
next := true;
exit
end;
AppendChar(c, w)
end
end;
procedure ReadStr(var s: pst);
var
w: pwts;
next: boolean;
begin
InitStr(s);
next := false;
while not next do
begin
InitWord(w);
ReadWord(w, next);
AppendStr(w, s);
end
end;
procedure WriteWord(var w: pwts);
var
t, t1: pwt;
begin
t := w.b;
while (t <> nil) do
begin
write(t^.c);
t1 := t;
t := t^.n;
dispose(t1)
end;
write(' ');
end;
procedure WriteStr(var s: pst);
var
t, t1: pst;
begin
t := s;
while (t <> nil) do
begin
WriteWord(t^.w);
t1 := t;
t := t^.n;
dispose(t1)
end;
writeln()
end;
var
s: pst;
begin
while not SeekEof do
begin
ReadStr(s);
WriteStr(s)
end
end.
wall a on sat Dumpty Humpty
Detailed notes - 2.10.5: Stack and queue
1
stack and queue describe behavior:
can be implemented using lists, arrays, circular buffers, or external storage
their identity is determined by operations and retrieval order
2
both store values and support insertion/extraction:
queue = FIFO: first in, first out
stack = LIFO: last in, first out
3
queue returns the oldest remaining value
stack returns the newest remaining value
4
singly linked implementations:
stack: insert and remove at the beginning
queue: append at the end; remove at the beginning
5
hide implementation behind subprograms:
clients use operations without depending on the representation
changing list storage to array storage should affect those subprograms alone
6
interface:
available procedures/functions plus the rules for using them
a good interface remains usable when implementation details change
7
design interface first:
start with the operations the user needs
choose a representation afterward
8
StackOfLongints:
one variable represents each independent stack
its eventual type can be a record or another suitable representation
give the type a name before committing to its contents
9
stack operations:
SOLPush(var stack; n): insert a longint
SOLPop(var stack; var n): remove the top value and return it through n
both receive the stack by reference because they change it
10
SOLIsEmpty(var stack): boolean
check before popping unless nonemptiness is already certain
by-reference parameter also avoids copying a potentially large representation
the contract excludes popping an empty stack
11
SOLInit makes a newly declared variable a valid empty stack
Deletion in a linked list becomes simpler when the program keeps a
pointer to the link that leads to the current node. The idea is to
modify the place where the current node is referenced, not only the
current node itself.
This technique is important in C; Pascal lets us learn the structure
before C makes pointer syntax unavoidable.
Detailed notes - 2.10.6: Traversing a list with a pointer to a pointer
1
remove every negative value:
removing the first node changes first
removing another node changes its predecessor's next
2
ordinary traversal loses the predecessor:
a predecessor-based loop needs separate handling for negative head nodes
an additional prev pointer reduces duplication but still needs a head special case
3
pointer to the incoming link: pp: ^itemptr
can contain @first or the address of any node's next field
pp^ = pointer to the current node; pp^^ = current node
start pp := @first
advance pp := @(pp^^.next)
4
advance only when keeping the current node:
after removal, the same incoming link already points to the next candidate
5
traverse while pp^ <> nil
removal:
tmp := pp^; pp^ := pp^^.next; dispose(tmp)
otherwise advance pp to the current node's next field
identical handling for first, interior, and consecutive removed nodes
a character trie selects a child using the next character; height depends on key length
8
search costs:
list: proportional to record count
balanced binary tree: proportional to log2(record count)
hash tables aim at constant expected lookup cost under suitable loading/distribution
9
hash function and table:
same key always gives the same hash; different keys should spread well
bucket/index = hash(key) mod table size
the example uses a generously sized array, commonly with prime length
10
collision:
different keys select the same position
empty position means absent key in the basic lookup scheme
chaining stores a list of colliding records at each table position
lists add allocation, linking, and traversal overhead
11
linear probing:
continue through successive positions until finding the key or an empty slot
insert in the first available slot
deleting an entry must preserve reachability of later entries in its probe chain
one method removes and reinserts the following cluster up to its first empty slot
12
load factor and resizing:
crowded tables spend more time resolving collisions
the book suggests staying below roughly two-thirds occupancy
grow the array and reinsert every record using the new modulus
resizing requires substantial work; old positions cannot simply be retained
13
dynamically sized arrays:
needed when the table capacity is chosen or changed during execution
available in modern Pascal dialects, beyond the subset covered here
More Recursion
Detailed notes - 2.11: More about recursion
1
strings, lists, and trees provide more substantial uses of recursion
revisit the technique with a larger set of programming tools
Mutual Recursion
Two subprograms may call each other. Pascal needs a forward
declaration when a name is used before its full body:
function IsOdd(n: integer): boolean; forward;
function IsEven(n: integer): boolean;
begin
if n = 0 then
IsEven := true
else
IsEven := IsOdd(n - 1);
end;
function IsOdd(n: integer): boolean;
begin
if n = 0 then
IsOdd := false
else
IsOdd := IsEven(n - 1);
end;
Detailed notes - 2.11.1: Mutual recursion
1
mutual recursion:
one subprogram calls another, which calls the first
the earlier definition needs information about the later subprogram
2
forward declaration:
header followed by forward; gives the name, parameters, and result type
contains no local declarations or body
lets the compiler check calls and generate argument conversions before seeing the implementation
3
declaration order:
declare the first subprogram forward
define the second, then provide the first subprogram's complete definition
both bodies can then refer to both names
4
every forward declaration requires a later matching definition
Towers of Hanoi
The recursive structure is:
move n - 1 disks from source to spare
move the largest disk from source to destination
move n - 1 disks from spare to destination
The number of moves is 2^n - 1.
Detailed notes - 2.11.2: Towers of Hanoi
1
implement the recursive algorithm introduced with the idea of an algorithm
2
task:
three rods; N differently sized disks initially stacked largest to smallest
move one disk at a time; never place a larger disk on a smaller one
transfer the whole stack using the fewest moves
3
recursive decomposition:
move n-1 disks from source to transit
move disk n from source to target
move n-1 disks from transit to target
base case n = 0: nothing to do
4
solve(source, target, transit, n):
recursive calls exchange rod roles as required
output identifies the disk and its source/target rods
validate the command-line disk count with val and require n >= 1
start solve(1, 3, 2, n)
5
alternative iterative algorithm:
odd moves: move the smallest disk around the rods
even disk count: 1 -> 2 -> 3 -> 1; odd count: reverse direction
even moves: perform the sole legal move excluding the smallest disk
6
apparently simple physical actions need explicit program state:
track which disks occupy each rod
compare top disks and handle empty rods
7
hanoi2 representation:
three singly linked lists, one per rod; array of head pointers
continue until rods 1 and 2 are empty
compute smallest-disk moves from the turn number
other moves find its rod, exclude it, then choose the legal direction between the remaining rods
8
iterative implementation is much longer:
bookkeeping dominates the concise recursive description
9
recursion can also be replaced by an explicit task stack:
preserve the original recursive decomposition
a loop processes stored unfinished tasks
10
task record:
disk count, source rod, target rod, state, and next pointer
StClearing: prepare to move the smaller disks away
StLargest: move the largest disk, then bring the smaller disks onto it
StFinal: task complete; remove it
processing:
start with one task transferring all disks from 1 to 3
in StClearing, change the current task to StLargest
if more than one disk remains, push the task for clearing n-1 disks
tasks remember where suspended work must resume
11
StLargest:
print the move of disk amount from src to dst
change the current task to StFinal
if needed, push a task moving smaller disks from transit to target
when a StFinal task returns to the front, unlink and dispose it
12
IntermRod(src, dst):
returns the rod number different from both src and dst
supplies the intermediate rod for each newly created subtask
13
hanoi3:
explicit task management is shorter than the first iterative approach
still substantially more code than the recursive solution
program hanoi;
procedure solve(source, target, interm, n: integer);
begin
if n = 0 then
exit;
solve(source, interm, target, n-1);
writeln(n, ': ', source, ' -> ', target);
solve(interm, target, source, n-1)
end;
var
n, code: integer;
begin
if ParamCount < 1 then
begin
writeln(ErrOutput, 'No parameters given');
halt(1)
end;
val(ParamStr(1), n, code);
if (code <> 0) or (n < 1) then
begin
writeln(ErrOutput, 'Invalid token count');
halt(1)
end;
solve(1, 3, 2, n)
end.
program hanoi2;
type
pdisk = ^disk;
disk = record
k: integer;
next: pdisk;
end;
RodsArray = array [1..3] of pdisk;
procedure MoveDiskItem(var RodFrom, RodTo: pdisk);
var
tmp: pdisk;
begin
tmp := RodFrom;
RodFrom := RodFrom^.next;
tmp^.next := RodTo;
RodTo := tmp
end;
procedure MoveDisk(var rods: RodsArray; src, dst: integer);
begin
writeln(rods[src]^.k, ': ', src, ' -> ', dst);
MoveDiskItem(rods[src], rods[dst])
end;
procedure MoveSmallest(var rods: RodsArray; turn, total: integer);
var
src, dst: integer;
begin
if total mod 2 = 0 then
begin
src := (turn div 2) mod 3 + 1;
dst := src + 1;
if dst = 4 then
dst := 1
end
else
begin
src := 3 - ((turn div 2 + 2) mod 3);
dst := src - 1;
if dst = 0 then
dst := 3
end;
MoveDisk(rods, src, dst)
end;
procedure MoveLarger(var rods: RodsArray);
var
src, dst, tmp: integer;
begin
src := 1;
dst := 2;
if (rods[1] <> nil) and (rods[1]^.k = 1) then
src := 3
else
if (rods[2] <> nil) and (rods[2]^.k = 1) then
dst := 3;
if (rods[src] = nil) or
((rods[dst] <> nil) and (rods[src]^.k > rods[dst]^.k)) then
begin
tmp := src;
src := dst;
dst := tmp
end;
MoveDisk(rods, src, dst)
end;
procedure solve(n: integer);
var
rods: RodsArray;
tmp: pdisk;
i: integer;
turn: integer;
begin
for i := 1 to 3 do
rods[i] := nil;
for i := n downto 1 do
begin
new(tmp);
tmp^.k := i;
tmp^.next := rods[1];
rods[1] := tmp
end;
turn := 1;
while (rods[1] <> nil) or (rods[2] <> nil) do
begin
if turn mod 2 = 1 then
MoveSmallest(rods, turn, n)
else
MoveLarger(rods);
turn := turn + 1
end
end;
var
n, code: integer;
begin
if ParamCount < 1 then
begin
writeln(ErrOutput, 'No parameters given');
halt(1)
end;
val(ParamStr(1), n, code);
if (code <> 0) or (n < 1) then
begin
writeln(ErrOutput, 'Invalid token count');
halt(1)
end;
solve(n)
end.
program hanoi3;
function IntermRod(src, dst: integer) : integer;
begin
if (src <> 1) and (dst <> 1) then
IntermRod := 1
else
if (src <> 2) and (dst <> 2) then
IntermRod := 2
else
IntermRod := 3
end;
procedure solve(n: integer);
type
TaskState = (StClearing, StLargest, StFinal);
ptask = ^task;
task = record
amount, src, dst: integer;
state: TaskState;
next: ptask;
end;
var
first, tmp: ptask;
begin
new(first);
first^.amount := n;
first^.src := 1;
first^.dst := 3;
first^.state := StClearing;
first^.next := nil;
while first <> nil do
begin
case first^.state of
StClearing:
begin
first^.state := StLargest;
if first^.amount > 1 then
begin
new(tmp);
tmp^.src := first^.src;
tmp^.dst := IntermRod(first^.src, first^.dst);
tmp^.amount := first^.amount - 1;
tmp^.state := StClearing;
tmp^.next := first;
first := tmp
end
end;
StLargest:
begin
first^.state := StFinal;
writeln(first^.amount, ': ', first^.src,
' -> ', first^.dst);
if first^.amount > 1 then
begin
new(tmp);
tmp^.src := IntermRod(first^.src, first^.dst);
tmp^.dst := first^.dst;
tmp^.amount := first^.amount - 1;
tmp^.state := StClearing;
tmp^.next := first;
first := tmp
end
end;
StFinal:
begin
tmp := first;
first := first^.next;
dispose(tmp)
end
end
end
end;
var
n, code: integer;
begin
if ParamCount < 1 then
begin
writeln(ErrOutput, 'No parameters given');
halt(1)
end;
val(ParamStr(1), n, code);
if (code <> 0) or (n < 1) then
begin
writeln(ErrOutput, 'Invalid token count');
halt(1)
end;
solve(n)
end.
Pattern Matching
Recursive pattern matching splits a string problem into:
the current character or pattern symbol
the rest of the string
the rest of the pattern
This is a useful example of recursion over text rather than
numbers.
A matcher for ? (any one character) and *
(any sequence). Ordinary characters advance in a loop; only
* recurses, trying every possible length for the part it
matches:
function MatchIdx(var str, pat: string; si, pi: integer): boolean;
var
i: integer;
begin
while true do
begin
if pi > length(pat) then
begin
MatchIdx := si > length(str);
exit
end;
if pat[pi] = '*' then
begin
for i := 0 to (length(str) - si + 1) do
if MatchIdx(str, pat, si+i, pi+1) then
begin
MatchIdx := true;
exit
end;
MatchIdx := false;
exit
end;
if (si > length(str)) or
((str[si] <> pat[pi]) and (pat[pi] <> '?')) then
begin
MatchIdx := false;
exit
end;
si := si + 1;
pi := pi + 1
end
end;
Show the complete program
program pattern;
function MatchIdx(var str, pat: string; si, pi: integer): boolean;
var
i: integer;
begin
while true do
begin
if pi > length(pat) then
begin
MatchIdx := si > length(str);
exit
end;
if pat[pi] = '*' then
begin
for i := 0 to (length(str) - si + 1) do
if MatchIdx(str, pat, si+i, pi+1) then
begin
MatchIdx := true;
exit
end;
MatchIdx := false;
exit
end;
if (si > length(str)) or
((str[si] <> pat[pi]) and (pat[pi] <> '?')) then
begin
MatchIdx := false;
exit
end;
si := si + 1;
pi := pi + 1
end
end;
function Match(str, pat: string): boolean;
begin
Match := MatchIdx(str, pat, 1, 1);
end;
begin
if ParamCount < 2 then
begin
writeln(ErrOutput, 'Two parameters expected');
halt(1)
end;
if Match(ParamStr(1), ParamStr(2)) then
writeln('yes')
else
writeln('no')
end.
yes
Detailed notes - 2.11.3: Pattern matching
1
match an entire string against a pattern:
ordinary character: matches itself
?: matches one arbitrary character
*: matches any sequence, including an empty sequence
a?c matches abc; a* matches any string beginning with a
2
work with unprocessed suffixes:
previously removed prefixes have already matched
when the pattern ends, succeed only if the string has also ended
program MatchPattern;
function MatchIdx(var str, pat: string; idxs, idxp: integer): boolean;
var
i: integer;
begin
while true do
begin
if idxp > length(pat) then
begin
MatchIdx := idxs > length(str);
exit
end;
if pat[idxp] = '*' then
begin
for i := 0 to length(str)-idxs+1 do
if MatchIdx(str, pat, idxs+i, idxp+1) then
begin
MatchIdx := true;
exit
end;
MatchIdx := false;
exit
end;
if (idxs > length(str)) or
((str[idxs] <> pat[idxp]) and (pat[idxp] <> '?')) then
begin
MatchIdx := false;
exit
end;
idxs := idxs + 1;
idxp := idxp + 1;
end
end;
function Match(str, pat: string): boolean;
begin
Match := MatchIdx(str, pat, 1, 1)
end;
begin
if ParamCount < 2 then
begin
writeln(ErrOutput, 'Two parameters expected');
halt(1)
end;
if Match(ParamStr(1), ParamStr(2)) then
writeln('yes')
else
writeln('no')
end.
program pattern;
function MatchIdx(var str, pat: string; si, pi: integer): boolean;
var
i: integer;
begin
while true do
begin
if pi > length(pat) then
begin
MatchIdx := si > length(str);
exit
end;
if pat[pi] = '*' then
begin
for i := 0 to (length(str) - si + 1) do
if MatchIdx(str, pat, si+i, pi+1) then
begin
MatchIdx := true;
exit
end;
MatchIdx := false;
exit
end;
if (si > length(str)) or
((str[si] <> pat[pi]) and (pat[pi] <> '?')) then
begin
MatchIdx := false;
exit
end;
si := si + 1;
pi := pi + 1
end
end;
function Match(str, pat: string): boolean;
begin
Match := MatchIdx(str, pat, 1, 1);
end;
begin
if ParamCount < 2 then
begin
writeln(ErrOutput, 'Two parameters expected');
halt(1)
end;
if Match(ParamStr(1), ParamStr(2)) then
writeln('yes')
else
writeln('no')
end.
Recursion on Lists and Trees
For a list:
base case: empty list
recursive case: process head, then process tail
For a binary tree:
base case: empty subtree
recursive case: process left subtree, root, and right subtree
Binary search trees use ordering to guide insertion and search.
Detailed notes - 2.11.4: Recursion with lists
1
recursive list structure:
either empty, or a first node followed by another list
sum:
empty list -> 0
otherwise p^.data + ItemListSum(p^.next)
recursion uses stack space proportional to list length; deep lists can overflow it
2
dispose recursively:
empty list -> return
dispose the tail first, then dispose the current node
preserves access to next until the recursive call has used it
3
sorted insertion:
empty list or first value > n: prepend n
otherwise recursively insert into p^.next
receive p as a var parameter so insertion can replace the incoming link
identical code handles the whole list and any tail
short-circuit evaluation protects p^.data when p = nil
Detailed notes - 2.11.5: Working with a binary search tree
1
recursive structure makes tree operations natural to express
2
TreeNode:
data: longint; left and right: pointers to TreeNode
root := nil represents an empty tree
sum:
empty tree -> 0
otherwise SumTree(left) + data + SumTree(right)
insertion:
pass the root pointer by reference
empty subtree: allocate a node and initialize both children to nil
smaller value: recurse left; larger: recurse right
duplicate value: report ok := false; successful insertion sets ok := true
membership:
same branch choices; nil means absent, equality means present
a function suits this operation because it does not change the tree
shared search operation:
TreeNodePos = ^TreeNodePtr
SearchTree(var p, val) returns the address of the link where val is or should be
return @p when p = nil or p^.data = val; otherwise recurse into the appropriate child
var p ensures @p denotes the caller's actual root/child link
using the returned position:
pos^ <> nil -> value already exists
pos^ = nil -> insert through new(pos^) and initialize pos^^
shared search removes duplicated traversal logic
these procedures do not prevent imbalance from unfavorable insertion order
3
further tree study in the source:
Wirth: Algorithms and Data Structures
Cormen, Leiserson, and Rivest: broader algorithm coverage
Knuth, volume 3: sorting and searching structures
4
nonrecursive exercise:
search needs only a loop following the appropriate child
full traversal must remember ancestors and unfinished work
an explicit stack can store the node and its processing state, as in Hanoi
5
full iterative traversal is a harder exercise and is revisited with C
program TreeDemo;
type
TreeNodePtr = ^TreeNode;
TreeNode = record
data: longint;
left, right: TreeNodePtr;
end;
TreeNodePos = ^TreeNodePtr;
function SearchTree(var p: TreeNodePtr; val: longint): TreeNodePos;
begin
if (p = nil) or (p^.data = val) then
SearchTree := @p
else
if val < p^.data then
SearchTree := SearchTree(p^.left, val)
else
SearchTree := SearchTree(p^.right, val)
end;
procedure AddToTree(var p: TreeNodePtr; val: longint; var ok: boolean);
var
pos: TreeNodePos;
begin
pos := SearchTree(p, val);
if pos^ = nil then
begin
new(pos^);
pos^^.data := val;
pos^^.left := nil;
pos^^.right := nil;
ok := true
end
else
ok := false
end;
function IsInTree(p: TreeNodePtr; val: longint): boolean;
begin
IsInTree := SearchTree(p, val)^ <> nil
end;
var
root: TreeNodePtr = nil;
c: char;
n: longint;
ok: boolean;
begin
while not eof do
begin
readln(c, n);
case c of
'?': begin
if IsInTree(root, n) then
writeln('Yes!')
else
writeln('No.')
end;
'+': begin
AddToTree(root, n, ok);
if ok then
writeln('Successfully added')
else
writeln('Couldn''t add!')
end;
else
writeln('I don''t know such command! Try "+" or "?"')
end
end
end.
Labels and goto
Labels mark statements as jump targets and need a consistent
indentation rule; outdenting a label to the surrounding block boundary
makes it stand out as non-sequential control flow.
Detailed notes - 2.12.6: Labels and goto
1
goto uses ordinary statement layout
label placement needs an explicit convention
2
a label marks a statement, including an empty statement
choose its indentation and whether its statement shares the line
3
common layout:
label aligned with the containing structure's boundary
labeled statement on the next line, with ordinary body indentation
a nested label need not be at the file's left margin
a same-line statement can work when a short label leaves normal alignment intact
4
alternative:
indent the label together with its statement
either keep both on one line or put the statement below
5
outdented labels are easier to recognize as special control-flow destinations
Detailed notes - 2.12.13: Keep the rules continuously
1
maintain readable formatting from the first source line onward
2
'fix the layout later' postpones help needed while writing the program
3
code is repeatedly read during development:
clear indentation reduces the effort of reconstructing its structure
neglecting layout creates errors and wastes debugging time
4
consistent practice makes formatting habitual
5
the author's rule: restore readability before judging or extending the program
6
repair indentation immediately after moving code or adding/removing control structures
learn the editor's block-indent and block-unindent commands
adjust the whole selected block instead of inserting spaces individually
Language and Character Set
Use ASCII in source code unless there is a strong reason not to.
Prefer English identifiers when the code may be read by tools, operating
systems, or other programmers.
Detailed notes - 2.12.1: ASCII and English
1
the book's source-code convention uses English names and comments
2
readers work in different environments:
operating systems, editors, encodings, display sizes, and languages differ
avoid assuming that a program will never leave its original setting
3
portability assumptions adopted by the book:
ASCII characters, English text, and an 80-column display
4
ASCII-only source convention:
plain Latin letters, digits, punctuation, underscore, and whitespace
excludes national alphabets, accented letters, and typographic punctuation
the author applies this convention even to comments and literals
compiler acceptance alone does not establish portability across the intended tools
5
common professional language:
the author requires English throughout source text
transliteration does not solve the problem of shared understanding
6
a shared specialist language serves the same purpose across national boundaries
7
English provides access to specifications, library documentation, protocols, and technical literature
8
three source conventions:
identifiers: English words or abbreviations
comments: English
user interface: English or designed for translation into multiple languages
9
develop enough English to read technical material and write understandable program text
10
localization:
keep translated messages in external resource files
load and display them as data
source-language conventions do not restrict which languages the program can process
11
Free Pascal has facilities for internationalized programs
omitted from this introduction; the book later demonstrates the topic with C
Indentation
Choose one consistent indentation style and keep it everywhere:
if condition then begin
statement1;
statement2;
end else begin
statement3;
end;
The indentation should show nesting. Do not rely on the editor to
hide inconsistent structure.
program CancelFraction;
type
num = int64;
function gcd(a, b: num) : num;
begin
while (a <> 0) and (b <> 0) do
if a > b then
a := a mod b
else
b := b mod a;
if a = 0 then
gcd := b
else
gcd := a
end;
var
x, y, d: num;
sign: boolean;
begin
readln(x, y);
if x < 0 then
begin
x := -x;
sign := true
end
else
sign := false;
if y < 0 then
begin
sign := not sign;
y := -y
end;
d := gcd(x, y);
if sign then
write('-');
writeln(x div d, ' ', y div d)
end.
Book exampleBook example: frcancel_test.shIn catalog
Make debug output easy to find and remove. Do not leave accidental
diagnostics in final output, especially in programs used in
pipelines.
Detailed notes - 2.13.3: Diagnostic output
1
when tests expose a failure, inspect what execution actually does
2
add temporary diagnostic statements:
did execution reach this point?
what value did this variable acquire?
3
make diagnostics recognizable:
prefix with DEBUG, XXX, or another distinctive marker
finish messages with newlines
buffering can otherwise hide a message, especially before a crash
4
output buffering:
output may wait until the buffer fills, the program exits, or it is explicitly flushed
flush(output) forces pending standard output out
terminal output has additional newline/input-related flushing behavior in the model described
5
debug statements follow the same structural indentation rules as ordinary code
6
keep reusable diagnostics under conditional compilation:
{$DEFINE DEBUG} defines a compilation symbol
{$IFDEF DEBUG} ... {$ENDIF} includes the enclosed code only when it is defined
alternatively compile with fpc -dDEBUG myprog.pas
enables/disables diagnostics without editing the source each time
7
complex structures need purposeful diagnostic routines:
print the state of a list, tree, or table clearly
conditionally compile the entire diagnostic routine if appropriate
gdb
Compile with debug information:
fpc -g program.pas
gdb ./program
Common debugger commands:
Command
Meaning
run
Start program
break name
Stop at procedure/function or line
next
Step over call
step
Step into call
print x
Show variable
backtrace
Show call stack
continue
Resume execution
Use the debugger to inspect what the program actually does, not what
it was intended to do.
Detailed notes - 2.13.4: The gdb debugger
1
debugger:
pauses execution, steps through code, and shows current values
2
debug information connects executable code with source concepts:
variable/subprogram names, source files, and source positions
without it, the debugger mostly sees machine-level information
3
compile the example with fpc -g myprog.pas
executable grows because it contains debugging information
4
gdb has its own command interpreter:
command editing, completion, and history
can launch a program, attach to a process, or analyze a crash dump
5
start gdb:
gdb ./myprog
gdb --args ./myprog abra schwabra kadabra supplies program arguments
6
start versus run:
start begins execution and stops at the main entry
run executes until termination, a breakpoint, or another stopping event
Ctrl-C interrupts the debugged program for inspection
a crash under the debugger exposes the current execution state
7
single-step commands:
next: advance at source level, running calls without entering them
step: enter called subprograms
Enter repeats the previous stepping command
8
list:
display source around the current position or another specified location
repeated listing allows inspection of a larger region
9
breakpoints:
break accepts a source location or subprogram name
stop before executing the corresponding operation
continue / cont resumes a paused program until the next stopping event
10
Pascal name handling:
the compiler/debugger combination used by the author exposes subprogram names in uppercase
use those names when setting breakpoints or referring to routines
11
breakpoint controls:
disable 3 / enable 3 toggles breakpoint 3
ignore 3 550 skips its next 550 hits
cond 5 I < 100 restricts breakpoint 5 to that condition
info breakpoints shows the current set and their properties
12
variable inspection and modification:
inspect displays a value
set var x:=50 changes x in the suspended program
13
backtrace / bt:
shows active calls, arguments, and where each call originated
helps reconstruct how execution reached the current routine
14
frame selection:
frame 1 selects the caller's context in the example
subsequent source listing and variable inspection use that frame
15
call:
invoke a program subroutine from the debugger
Pascal-specific value support can be limited; a string variable may work where a literal does not
16
quit or Ctrl-D exits; help describes debugger commands
17
attach to an existing process:
gdb ./myprogram 2765 in the source's example
executable supplies symbols; process supplies the live state
inspect calls/values, set breakpoints, and resume as needed
18
core-file analysis:
revisited with C
the Free Pascal runtime described handles many failures itself, so those failures do not produce an ordinary core dump
Modules and Separate
Compilation
Large programs should be split into modules. A Pascal module is a
unit.
Detailed notes - 2.14: Modules and separate compilation
1
splitting a growing program into files:
makes navigation and focused work easier
supports reuse and correction of shared components
2
textual inclusion:
{$I myfile.pas} inserts that file's contents at the directive
3
inclusion alone leaves one translation unit:
all included text is compiled together
repeated whole-program compilation wastes time
large global name sets increase collision risks
4
separate compilation:
divide code into modules, usually source files with related subprograms
compile each independently to object code
linker combines object files into the executable
5
module visibility:
export names clients need; hide internal names
different modules can reuse private names without exposing a conflict to clients
Units
Basic unit shape:
unit counter;
interface
procedure IncCounter;
function GetCounter: integer;
implementation
var
value: integer;
procedure IncCounter;
begin
value := value + 1;
end;
function GetCounter: integer;
begin
GetCounter := value;
end;
begin
value := 0;
end.
Use it from a program:
program demo;
uses
counter;
begin
IncCounter;
writeln(GetCounter);
end.
The interface section is the public contract. The
implementation section is private code and data.
Detailed notes - 2.14.1: Pascal units
1
main module versus unit:
main program uses program; other modules begin with unit myunit;
uses myunit imports its interface
the main program's uses follows its header and lists multiple units with commas
follow the filename convention mymodule.pp for unit mymodule
2
interface section:
exported constants, types, variables, and subprogram headers
subprogram bodies do not belong here
3
implementation section:
definitions of exported subprograms
private helpers, types, constants, and variables
4
interface is a contract:
document every exported facility and the rules for using it
changing existing interface behavior can break clients
5
implementation is hidden from client use:
may be changed while preserving the contract
internal design details need not enter user-facing interface documentation
6
limit exported names:
lowers collision risk as modules are reused in larger programs
7
private visibility also prevents accidental misuse:
clients cannot directly call hidden helpers or mutate hidden variables
8
encapsulation:
hide implementation details behind a stable, functioning interface
9
unit ends with end.
an optional begin ... end. initialization section runs before the main program
useful when unit state requires initialization
10
lngtree example:
export TreeNode, TreeNodePtr, AddToTree, and IsInTree
keep TreeNodePos and SearchTree private in implementation
program UnitDemo;
uses lngtree;
var
root: TreeNodePtr = nil;
c: char;
n: longint;
ok: boolean;
begin
while not eof do
begin
readln(c, n);
case c of
'?': begin
if IsInTree(root, n) then
writeln('Yes!')
else
writeln('No.')
end;
'+': begin
AddToTree(root, n, ok);
if ok then
writeln('Successfully added')
else
writeln('Couldn''t add!')
end;
else
writeln('Unknown command "', c, '"')
end
end
end.
Units Using Other Units
A unit can have its own uses clauses. Keep dependencies
intentional:
put a dependency in interface only when public
declarations need it
put a dependency in implementation when only private
code needs it
This keeps recompilation and coupling smaller.
Detailed notes - 2.14.2: Units using other units
1
implementation dependency:
put uses immediately after implementation
imported facilities become available to internal code
2
interface dependency:
an exported declaration may need another unit's type or constant
examples: parameter/result type, array bound, or exported record-based type
3
put such uses immediately after interface
interface dependencies must not form a cycle
4
avoid unnecessary cross-dependencies:
where reciprocal use is needed, keep it in implementation sections when possible
interface dependencies expose more coupling to clients
Module as Architecture
A good module collects one responsibility:
stack operations
input parsing
screen interaction
tree storage
file format handling
The module boundary should hide representation details. Users of a
stack should not need to know whether it is implemented by an array or a
linked list.
Detailed notes - 2.14.3: A module as an architectural unit
1
module boundaries should follow deliberate rules
2
one module's facilities should be logically related:
larger programs need a comprehensible division into subsystems
3
responsibility test:
explain what the module/subsystem does in one phrase
two unrelated responsibilities suggest splitting the module
4
public name prefixes:
a shared subsystem prefix helps distinguish exported identifiers
Comments