📝 Pascal Fundamentals
🎯 What is Pascal?
Pascal is an imperative and procedural programming language designed by Niklaus Wirth in 1970. It was named after Blaise Pascal and designed to encourage good programming practices using structured programming and data structuring.
Key concept: Pascal emphasizes strong typing, structured programming, and program readability, making it ideal for teaching and software development.
Deep Explanation
Pascal is a foundational language in computer science education. It introduced concepts like structured control flow, data types, and modular programming that influenced many modern languages.
Why it matters: Pascal taught generations of programmers disciplined, structured programming and influenced languages like Ada, Modula-2, and Delphi.
program HelloWorld;
begin
writeln('Hello, World!');
end.
program SimpleMath;
var
a, b, sum: integer;
begin
a := 5;
b := 10;
sum := a + b;
writeln('Sum: ', sum);
end.📋 Syntax & Structure
🎯 Pascal Program Structure
Pascal programs have a well-defined structure with program headers, declaration sections, and a body. The syntax is English-like and easy to read.
Program Structure
Program header: 'program' name; Uses clause: Include units. Declaration section: Constants, types, variables, procedures. Body: begin ... end. Statements: End with semicolon.
Case sensitivity: Pascal is case-insensitive (unlike many modern languages).
program ProgramStructure;
uses
SysUtils; { Uses the System Utilities unit }
const
PI = 3.14159; { Constant declaration }
type
TIntegerArray = array[1..10] of integer; { Type declaration }
var
count: integer; { Variable declaration }
numbers: TIntegerArray;
procedure SayHello; { Procedure declaration }
begin
writeln('Hello from Pascal!');
end;
begin
SayHello; { Program body }
count := 1;
numbers[count] := 42;
writeln('Number: ', numbers[count]);
end.📊 Data Types
🎯 Pascal Data Types
Pascal has a rich set of data types including simple types (integer, real, char, boolean), structured types (arrays, records, sets), and pointer types.
Type System
Integer: Whole numbers (byte, shortint, word, longint). Real: Floating-point numbers (single, double, extended). Char: Single character. Boolean: True or False. String: Sequence of characters.
User-defined: Enumerated types, subranges, records, arrays.
program DataTypes;
type
TWeekDay = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
TYearRange = 1900..2100;
TPerson = record
name: string[50];
age: integer;
birthday: TYearRange;
end;
var
i: integer;
r: real;
c: char;
b: boolean;
s: string;
day: TWeekDay;
person: TPerson;
begin
i := 42;
r := 3.14;
c := 'A';
b := true;
s := 'Hello Pascal';
day := Friday;
person.name := 'Alice';
person.age := 30;
person.birthday := 1990;
end.📦 Variables & Constants
🎯 Storing Data
Variables store data that can change during program execution. Constants store values that never change.
Declaration Rules
Variable: var name: type; Constant: const name = value; Scope: Global (program-level) or local (within procedures). Initialization: Variables can be initialized in the declaration.
Typed constants: Constants with explicit types (in some Pascal dialects).
program VariablesConstants;
const
MAX_VALUE = 100;
MESSAGE = 'Welcome to Pascal';
PI = 3.14159265359;
var
counter: integer = 0;
price: real;
name: string;
is_active: boolean;
procedure LocalVariables;
var
local_var: integer;
begin
local_var := 10;
writeln('Local: ', local_var);
end;
begin
price := 99.99;
name := 'Product';
is_active := true;
writeln(MESSAGE);
writeln('Counter: ', counter);
counter := counter + 1;
end.🔄 Control Structures
🎯 Flow Control
Pascal provides structured control flow with conditionals (if-then-else, case) and loops (while, repeat, for).
Control Flow
If-then-else: if condition then statement else statement. Case: case expression of value: statement; While: while condition do statement. Repeat-until: repeat statements until condition. For: for variable := start to end do statement.
Nested control: Can be nested arbitrarily.
program ControlStructures;
var
i, score: integer;
grade: char;
begin
{ If-then-else }
score := 85;
if score >= 90 then
grade := 'A'
else if score >= 80 then
grade := 'B'
else if score >= 70 then
grade := 'C'
else
grade := 'F';
writeln('Grade: ', grade);
{ Case statement }
case grade of
'A': writeln('Excellent!');
'B': writeln('Good!');
'C': writeln('Average');
'F': writeln('Needs improvement');
end;
{ For loop }
for i := 1 to 5 do
writeln('i = ', i);
{ While loop }
i := 1;
while i <= 5 do
begin
writeln('While: ', i);
i := i + 1;
end;
{ Repeat-until }
i := 1;
repeat
writeln('Repeat: ', i);
i := i + 1;
until i > 5;
end.⚙️ Procedures & Functions
🎯 Modular Programming
Procedures (no return value) and functions (return a value) are the building blocks of modular programming in Pascal.
Subprogram Details
Parameters: Value parameters (default), variable parameters (var), const parameters. Return: Functions return via the function name or Result variable (in some dialects). Recursion: Subprograms can call themselves.
Overloading: Not supported in standard Pascal (but in Object Pascal).
program ProceduresFunctions;
{ Procedure - no return value }
procedure PrintMessage(msg: string);
begin
writeln('Message: ', msg);
end;
{ Procedure with var parameter }
procedure Swap(var a, b: integer);
var
temp: integer;
begin
temp := a;
a := b;
b := temp;
end;
{ Function with return value }
function Factorial(n: integer): integer;
begin
if n <= 1 then
Factorial := 1
else
Factorial := n * Factorial(n - 1);
end;
{ Function with multiple parameters }
function Max(a, b: integer): integer;
begin
if a > b then
Max := a
else
Max := b;
end;
var
x, y: integer;
begin
x := 5;
y := 10;
PrintMessage('Hello');
Swap(x, y);
writeln('After swap: x=', x, ' y=', y);
writeln('Factorial(5): ', Factorial(5));
writeln('Max(7, 3): ', Max(7, 3));
end.📚 Arrays
🎯 Array Data Structure
Arrays in Pascal are homogeneous collections of elements of the same type, accessed by index.
Array Types
Static arrays: Fixed size declared at compile time. Dynamic arrays: Size can be changed at runtime (in Object Pascal). Multi-dimensional: Arrays of arrays. Packed arrays: Memory-efficient storage.
Array operations: Looping, sorting, searching.
program Arrays;
type
TIntArray = array[1..10] of integer;
TStringArray = array[1..5] of string;
TMatrix = array[1..3, 1..3] of integer;
var
numbers: TIntArray;
names: TStringArray;
matrix: TMatrix;
i, j: integer;
begin
{ Initialize array }
for i := 1 to 10 do
numbers[i] := i * i;
{ Print array }
for i := 1 to 10 do
writeln('numbers[', i, '] = ', numbers[i]);
{ String array }
names[1] := 'Alice';
names[2] := 'Bob';
names[3] := 'Charlie';
for i := 1 to 3 do
writeln('Name: ', names[i]);
{ 2D array }
for i := 1 to 3 do
for j := 1 to 3 do
matrix[i][j] := i * j;
for i := 1 to 3 do
begin
for j := 1 to 3 do
write(matrix[i][j]:4);
writeln;
end;
end.📋 Records
🎯 Record Data Structure
Records are composite data types that group different types of data into a single unit.
Record Details
Fields: Named components of different types. Variant records: Overlapping fields (like unions in C). Nested records: Records inside records. With statement: Simplifies field access.
Applications: Representing entities like students, products, employees.
program Records;
type
TAddress = record
street: string[50];
city: string[30];
zip: string[10];
end;
TEmployee = record
id: integer;
name: string[50];
salary: real;
address: TAddress; { Nested record }
end;
TShape = record
case kind: char of
'R': (width, height: real);
'C': (radius: real);
'S': (side: real);
end;
var
emp: TEmployee;
shape: TShape;
begin
emp.id := 1001;
emp.name := 'John Doe';
emp.salary := 75000.0;
emp.address.street := '123 Main St';
emp.address.city := 'Boston';
emp.address.zip := '02101';
writeln('ID: ', emp.id);
writeln('Name: ', emp.name);
writeln('Salary: ', emp.salary:8:2);
writeln('Street: ', emp.address.street);
{ With statement for easier access }
with emp do
begin
writeln('City: ', address.city);
writeln('Zip: ', address.zip);
end;
{ Variant record }
shape.kind := 'C';
shape.radius := 5.0;
writeln('Circle radius: ', shape.radius:6:2);
end.📍 Pointers
🎯 Memory Management
Pointers in Pascal are variables that store memory addresses. They enable dynamic memory allocation and advanced data structures.
Pointer Details
Declaration: var p: ^type; Allocation: New(p); Deallocation: Dispose(p); Dereference: p^ to access the value.
Nil pointers: Pointers that point to nothing. Linked lists: Common use of pointers.
program Pointers;
type
PNode = ^TNode;
TNode = record
data: integer;
next: PNode;
end;
var
head, current, newNode: PNode;
i: integer;
begin
{ Create a linked list }
head := nil;
{ Add nodes (push) }
for i := 1 to 5 do
begin
New(newNode);
newNode^.data := i;
newNode^.next := head;
head := newNode;
end;
{ Traverse and print }
current := head;
while current <> nil do
begin
writeln('Node data: ', current^.data);
current := current^.next;
end;
{ Free memory }
while head <> nil do
begin
current := head;
head := head^.next;
Dispose(current);
end;
end.💾 File I/O
🎯 Reading and Writing Files
Pascal provides text and binary file I/O for persistent data storage. Files are handled through file variables.
File Operations
Text files: Read/Write lines of text. Assign: Associate file variable with filename. Reset: Open for reading. Rewrite: Open for writing. Append: Open for appending.
Binary files: Read/Write raw data of any type.
program FileIO;
var
f: text;
line: string;
data: integer;
begin
{ Write to a text file }
assign(f, 'data.txt');
rewrite(f);
writeln(f, 'Hello from Pascal!');
writeln(f, 'Line 2');
writeln(f, 'Line 3');
close(f);
{ Read from a text file }
assign(f, 'data.txt');
reset(f);
while not eof(f) do
begin
readln(f, line);
writeln('Read: ', line);
end;
close(f);
{ Read numeric data }
assign(f, 'numbers.txt');
rewrite(f);
writeln(f, '10');
writeln(f, '20');
writeln(f, '30');
close(f);
assign(f, 'numbers.txt');
reset(f);
while not eof(f) do
begin
readln(f, data);
writeln('Number: ', data);
end;
close(f);
end.📦 Units
🎯 Modular Code Organization
Units in Pascal are separate compilation modules that contain constants, types, variables, procedures, and functions.
Unit Structure
Interface: Public declarations (visible to other units). Implementation: Private code (hidden). Initialization: Code run when the unit is loaded. Uses clause: Import other units.
Examples: SysUtils, DateUtils, Math.
{ Unit: MyUtils.pas }
unit MyUtils;
interface
{ Public declarations }
function Add(a, b: integer): integer;
function Multiply(a, b: integer): integer;
procedure PrintMessage(msg: string);
implementation
{ Private implementation }
function Add(a, b: integer): integer;
begin
Add := a + b;
end;
function Multiply(a, b: integer): integer;
begin
Multiply := a * b;
end;
procedure PrintMessage(msg: string);
begin
writeln(msg);
end;
initialization
writeln('MyUtils unit initialized');
finalization
writeln('MyUtils unit finalized');
end.
{ Main program using the unit }
program UnitDemo;
uses
MyUtils;
var
x, y: integer;
begin
x := 10;
y := 5;
writeln('Add: ', Add(x, y));
writeln('Multiply: ', Multiply(x, y));
PrintMessage('Hello from unit!');
end.🏛️ Object-Oriented Pascal
🎯 OOP Extensions
Object Pascal (Delphi) adds object-oriented features to standard Pascal, including classes, inheritance, and polymorphism.
OOP Features
Classes: Define objects with properties and methods. Inheritance: Extend base classes. Polymorphism: Virtual and abstract methods. Interfaces: Multiple interface inheritance.
Examples: Delphi, Free Pascal, Turbo Pascal.
program OOPExample;
type
TShape = class
private
FName: string;
public
constructor Create(AName: string);
function Area: real; virtual; abstract;
function Perimeter: real; virtual; abstract;
procedure Display; virtual;
property Name: string read FName write FName;
end;
TCircle = class(TShape)
private
FRadius: real;
public
constructor Create(AName: string; ARadius: real);
function Area: real; override;
function Perimeter: real; override;
procedure Display; override;
end;
constructor TShape.Create(AName: string);
begin
FName := AName;
end;
procedure TShape.Display;
begin
writeln('Shape: ', FName);
end;
constructor TCircle.Create(AName: string; ARadius: real);
begin
inherited Create(AName);
FRadius := ARadius;
end;
function TCircle.Area: real;
begin
Area := 3.14159 * FRadius * FRadius;
end;
function TCircle.Perimeter: real;
begin
Perimeter := 2 * 3.14159 * FRadius;
end;
procedure TCircle.Display;
begin
writeln('Circle: ', FName, ', Radius: ', FRadius:6:2);
writeln('Area: ', Area:6:2, ', Perimeter: ', Perimeter:6:2);
end;
var
shape: TShape;
begin
shape := TCircle.Create('MyCircle', 5.0);
shape.Display;
shape.Free;
end.💼 Applications
🎯 Where Pascal is Used
Pascal is used in education, legacy systems, scientific computing, and application development (especially Delphi).
Application Domains
Education: Teaching programming fundamentals. Scientific computing: Numerical analysis. Desktop applications: Delphi-based Windows apps. Embedded systems: Some industrial applications.
Legacy: Many older systems still run on Pascal.
program ScientificApplication;
uses
Math;
{ Calculate statistical metrics }
function Mean(data: array of real): real;
var
i: integer;
sum: real;
begin
sum := 0;
for i := 0 to Length(data) - 1 do
sum := sum + data[i];
Mean := sum / Length(data);
end;
function StdDev(data: array of real; mean: real): real;
var
i: integer;
sum: real;
begin
sum := 0;
for i := 0 to Length(data) - 1 do
sum := sum + (data[i] - mean) * (data[i] - mean);
StdDev := sqrt(sum / Length(data));
end;
var
values: array[0..4] of real = (1.0, 2.0, 3.0, 4.0, 5.0);
avg, sd: real;
begin
avg := Mean(values);
sd := StdDev(values, avg);
writeln('Mean: ', avg:6:2);
writeln('StdDev: ', sd:6:2);
end.🚀 Future Directions
🎯 Pascal Today and Tomorrow
Pascal continues to evolve with Free Pascal, Lazarus, and Delphi bringing modern features to the language.
Modern Pascal
Free Pascal: Open-source compiler with many extensions. Lazarus: Cross-platform RAD IDE. Delphi: Commercial IDE with modern features. Language extensions: Generics, anonymous methods, operator overloading.
Community: Active community maintaining and evolving the language.
program ModernPascal;
{ Example of generics in Free Pascal }
uses
Generics.Collections;
var
list: specialize TList;
i: integer;
begin
list := specialize TList.Create;
try
for i := 1 to 10 do
list.Add(i);
for i in list do
writeln('Item: ', i);
finally
list.Free;
end;
end.
{ Anonymous methods (Delphi) }
program AnonMethods;
uses
System.SysUtils;
var
f: TFunc;
result: integer;
begin
f := function(x: integer): integer
begin
Result := x * x;
end;
result := f(5);
writeln('Square: ', result);
end.