0% found this document useful (0 votes)
14 views65 pages

Algorithms and Programming

Uploaded by

Paulo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views65 pages

Algorithms and Programming

Uploaded by

Paulo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Algorithms &

programming

SOFTWARE ENGINEERING - LEVEL I


Author: MANDA TABI PAUL CYRILLE Application Developer & IT Specialist

Phone : 695744632
[email protected]

September 2025
Table of Contents
1. Introduction to Programming Logic and Coding Languages
2. Basic Structures in Pascal
3. Functions and Procedures
4. Arrays and Linear Data Structures
5. Algorithmic Approaches
6. Fundamental Algorithms
7. Practical Exercises and Applications

P a g e 1 | 65
CHAPTER 1: Introduction to
Programming Logic and Coding
Languages
Programming logic, also called Algorithmic, is a method for solving
problems following a determined sequence of operational
rules. It is the description of a process. It corresponds to a sequence of
steps whose execution achieves a set goal. Its implementation solves a
given problem.

Example: Following a cooking recipe.

1. Introduction to Algorithms
1.1 What is an Algorithm?

An algorithm is a finite sequence of instructions to solve a


problem.

An algorithm is a description in natural language of the sequence


of actions performed by a program.

An algorithm can be defined as the sequence of actions leading to


a specific result from a given situation.

It is essential for:

 Optimizing resources (time, memory).


 Structuring the problem-solving logic.
 Ensuring the reproducibility of results.

1.2 Notion of Algorithm and Problem

Using top-down analysis, this involves repeatedly breaking down each


action into sub-actions by asking three types of questions at each step:

Statement of problem:
• Input: A sequence of n numbers <a1, a2, …, an>
• Output: A reordering of the input sequence <a´1,
a´2, …, a´n> so that a´i ≤ a´j whenever i < j
Instance: The sequence <5, 3, 2, 8, 3>
Algorithms:
• Selection sortP a g e 2 | 65
• Insertion sort
• Merge sort
• (many others)
 What do we want to do? What results do we want to obtain?
 How to do it? What variables, types, operations, and
processing should be applied to the base data to obtain
the required results?
o The action is broken down into sub-actions.
o What abstract method can be used to perform the action?
o What decomposition model should we use to perform this
action using the chosen method?
o What objects are needed to allow this decomposition?
(variables, types, domains, etc.)
 Are we doing what we intended? Proof of validity.

Practical Example: Write an algorithm to calculate the average of


three grades.

Input Data (Subjectsmarks & Coefficients):

Processing (translates all human actions applied to solve the


problem):

Step 1: grdSubject1 = S1 * C1, grdSubject2 = S2 * C2, grdSubject3 =


S3 * C3
Step 2: TotalGradeSubject = grdSubject1 + grdSubject2 + grdSubject3
Step 3: TotalGroupCoef = C1 + C2 + C3
Step 4: Average = TotalGradeSubject / TotalGroupCoef
Step 5: Display Average

Role of the Algorithm:

 Simple Calculation: Shows how to break down a problem into


clear steps.
 Basis for Beginners: Illustrates the structure of an algorithm
(input, processing, output).

1.3 Program Design Process

The design of a program that must solve a given problem should follow
the following steps:

Problem Statement
Analysis P a g e 3 | 65
Algorithm

Coding
Note that each program (algorithm) must have a name and must have
three parts: Header, Declarative Part, and Program Body.

The analysis phase and the translation phase are intellectual human
operations, while the compilation and execution phases are performed
automatically by the machine.
A semantic error is a fault due to a poor design of the method
followed to solve the problem (analysis phase); it is related to logic.
Here, it is a program that does not meet the client's or user's
expectations, so the algorithm must be corrected from the analysis
phase.
A syntax error is a spelling or grammar mistake. It is made in the
coding phase and is reported by the compiler when it cannot interpret
an instruction from the source program to translate it into machine
language (assembly language). Here, the program cannot execute (no
executable program).

1.4 Structure of an Algorithm

Every algorithm has the following three parts: the algorithm's name,
the declarative part, and the algorithm's body.

 Algorithm Name: It identifies it. This name will always be


written as a single word, and it has the same characteristics as a
variable name. It will always be preceded by the word
"ALGORITHM".
Example 1: ALGORITHM Factorial
Example 2: ALGORITHM SquareRoot

 Declarative Part: This part will contain the declaration of all the
variables we will use in the algorithm.
 Algorithm Body: The body of an algorithm includes:
initialization (assigning starting values to different variables),
execution (applying the processing or executing the different
P a g e 4 | 65
primitive actions of the problem), and returning results
(displaying or returning the obtained results).

We can represent the algorithm as follows:

ALGORITHM NAME

DECLARATIVE PART

INITIALIZATION May or may not exist

EXECUTION

Algorithm Body
RETURNING
RESULTS

Algorithm Syntax: Pseudocode

Here is the syntax of an algorithm:

ALGORITHM AlgorithmName
{ Declarative Part
Start
{ Algorithm Body
Stop

Example:

Algorithm "algorithm name"


Constant SET "constant name" to "constant value"
Variable SET "variable1 name" of "typeName1"
SET "variable2 name" of " typeName2"
SET "variable3 name" of " typeName3"
SET "variable n name" of " typeName n"
Start
"instruction1"
"instruction2"
"instruction3"
"instruction n"
Stop.

P a g e 5 | 65
Example:

Step Instructions States of variables


N° values
Algorithm: calculateAverage C C G Av
C2 G1 G3
1 3 2 g
Step Start
1
Step Set coef1 to 3, Set coef2 to 1, Set 3 1 5
2 coef3 to 5
Step initialize Avg = 0 3 1 5 0
3
Step Input grade1, grade2, grade3 3 1 5 10 1 11 0
4
4
Step Avg ← grade1 * coef1 + grade2 * 3 1 5 10 1 11 11
4
5 coef2 + grade3 * coef3 /( coef1+
coef2+ coef3)
Step Display("The average is: ", Avg) 3 1 5 10 1 11 11
4
6
Step Stop.
7

Graphical Representation of an Algorithm: Flowchart

Flowchart: Graphical translation of the algorithm. Sometimes called a


flow diagram or flowchart.

Flowchart symbols: oval (start/end), rectangle (processing), diamond


(decision), parallelogram (input/output).

Previous Example: START

Coef1=3 Coef2=1 Coef3=5


Avg=0

Read grade1,
grade2, grade3
P a g e 6 | 65

Avg ← grade1 * coef1 +


grade2 * coef2 + grade3 *
2. Notion of Programming
 Computer Programming: It is a sequence of instructions
(commands, functions, etc.) written in a programming language
(following the required rules and syntax) and executed by a
computer to solve a given problem.

It represents the translation of an algorithm using a programming


language.

 Programming Language: A set of commands, functions, and


described rules, construction rules, syntax rules to be used to
develop computer programs.

Pascal Program:
program CalculateAverage;

P a g e 7 | 65
uses CRT;

{ This program calculates the average of three grades entered by the user. It
illustrates the use of variables, constants, input/output, and basic calculations. }

const
coef1 = 3; coef2 = 2; coef3 = 5; { Assigning values to different constants }

var
grade1, grade2, grade3, Avg: real; { Declaring variables for grades and
average }

begin
ClrScr;
writeln('Enter three grades: '); { Asks the user to enter the grades }
readln(grade1, grade2, grade3); { Reads the three grades }
Avg := (grade1 * coef1 + grade2 * coef2 + grade3 * coef3) / (coef1 + coef2 + coef3); {
Calculates the average }
writeln('The average is: ', Avg:2:2); { Displays the average with 2
decimal places }
ReadKey;
end.

 Procedural Programming is a method that uses top-down


analysis to solve a problem by breaking down the problem into
sub-problems until very simple actions, also called procedures,
are identified.

In procedural programming, the code is organized into reusable blocks


called procedures or functions. Each function performs a specific task
and can be called from different parts of the program.

Using functions promotes modularity, allowing developers to break


down complex problems into smaller, more manageable parts. This
makes the code easier to understand, maintain, and debug.

We can therefore understand here that a procedure is a sequence of


instructions grouped under the same name, which can be called to
perform a specific task.

A procedural programming language is a language that uses sets of


functions and commands to perform actions.

2.1 Different Types of Programming Languages

P a g e 8 | 65
In general, each programming language is linked to a particular type of
programming:

Programming Functional Characteristics Associated


Type Programming
Language
Examples
Procedural | Involves writing and executing GOBOL C
Programming (With instructions one after the other
Procedures) (sequential order) BASIC PASCAL

Factual Allows developing graphical VISUAL BASIC C#


Programming interface applications (by executing
events) VISUAL C++

Object-Oriented Based on writing and reusing C++ JAVA


Programming related components (objects and
(OOP) object classes)

Data Manipulation Allows manipulating information in SQL (Structured


Programming relational databases Query Language)

Script Enhances the functionality of web Javascript


Programming pages written in a language (HTML)

Tag Programming Allows formatting electronic HTML (Hypertext


documents to be used on the Makup Language)
internet. Coding web pages using
formatting commands XML (Extended

Makup Language)

Web Programming Allows designing, assembling, and PHP,JAVA,ASP


developing websites

CHAPTER 2: Algorithm Design


Techniques /Strategies
1. Classification by Implementation
Method
P a g e 9 | 65
Algorithms can be classified according to how they are implemented:

 Recursive or Iterative: A recursive algorithm calls itself until


it reaches a base condition (e.g., Tower of Hanoi), while an
iterative algorithm uses loops or data structures like stacks or
queues (e.g., Stock Span problem). Both approaches are
interchangeable, but the choice often depends on readability and
efficiency.
 Exact or Approximate: Exact algorithms always find an
optimal solution (e.g., quicksort), while approximate algorithms
are used for complex problems (such as NP-hard problems)
where an optimal solution is difficult to obtain. They provide a
solution "close" to the optimum (e.g., algorithms for the traveling
salesman problem).
 Serial, Parallel, or Distributed: Serial algorithms execute
one instruction at a time. Parallel algorithms divide the problem
into sub-problems executed simultaneously on multiple
processors. Distributed algorithms distribute these sub-
problems across multiple machines (e.g., massive calculations in
big data).

Role: These classifications help choose the most suitable method


based on hardware constraints (memory, number of processors) and
the nature of the problem (size, complexity).

2. Classification by Design Method


This category groups the strategies used to design efficient algorithms:

 Brute Force: Tests all possible solutions until the correct one is
found. Simple but often inefficient for large problems.
 Divide and Conquer: Divides the problem into sub-problems,
solves them recursively, and then combines the results (e.g.,
merge sort, quicksort).
 Dynamic Programming: Optimizes recursive calls by storing
intermediate results in a table to avoid redundant calculations
(e.g., 0-1 knapsack problem).
 Greedy: Makes locally optimal decisions at each step, without
guaranteeing global optimality (e.g., activity selection, fractional
knapsack).
 Backtracking: Explores all possible solutions by backtracking if
a path does not lead to a solution (e.g., N-queens problem).
 Branch and Bound: Used for combinatorial optimization
problems. It explores the solution space by eliminating non-
promising branches (e.g., traveling salesman problem).

P a g e 10 | 65
 Transformation and Conquest: Transforms a complex
problem into a known, already solved problem (e.g., finding the
median by first sorting the list).
 Iterative Improvement: Gradually improves an initial solution
(e.g., simplex algorithm in linear programming).

Role: These methods guide the choice of algorithm based on the


problem's structure (optimization, combinatorial, etc.) and available
resources.

3. Design Approaches
 Top-Down Approach: Breaks down a complex problem into
simpler sub-problems until elementary solutions are obtained.
 Bottom-Up Approach: First solves the simplest sub-problems,
then combines them to solve the overall problem.

Role: These approaches help structure problem-solving by facilitating


modeling and implementation.

4. Other Classifications
 Randomized Algorithms: Use random choices to speed up
resolution (e.g., randomized quicksort).
 Complexity Classification: Algorithms are analyzed based on
their execution time (e.g., O(n), exponential). This allows
comparing their theoretical efficiency.
 Classification by Research Domain: Each domain (operations
research, artificial intelligence, machine learning) has its own
specialized algorithms (e.g., sorting algorithms for databases,
learning algorithms for AI).
 Enumeration and Backtracking: Used in artificial intelligence
to explore complex solution spaces.

Role: These classifications situate an algorithm in a scientific or


applicative context and evaluate its suitability for specific problems.

Summary

Algorithms are classified to facilitate their selection based on


needs:

 Efficiency (time, memory),


 Nature of the problem (optimization, search, decision),
 Hardware constraints (serial, parallel, distributed),
P a g e 11 | 65
 Solution guarantee (exact or approximate).

Understanding these classifications allows selecting or designing


the most suitable algorithm for a given problem, balancing speed,
precision, and resources. For example, a combinatorial optimization
problem might use Branch and Bound, while a sorting problem would
opt for a divide and conquer algorithm like merge sort.

CHAPTER 3: Basic Notions for


Developing Algorithms
1. Definitions
Algorithm: Description in natural language of the sequence of actions
performed by a program.

Flowchart: Graphical translation of the algorithm. Sometimes called a


flow diagram or flowchart.

Syntax: Writing rules of a given language.

Data Type:

A program may handle different types of data:

 Boolean: Value that can be either True or False.


 Integer: Whole numeric values that can be signed or unsigned
(encoded on one or more bytes).
 Real: Numeric values encoded with a mantissa and an exponent.
 Character: Byte corresponding to an ASCII code.
 String: Set of characters.
 Data Array: Set of data of the same type (e.g., array of
integers, array of reals).

All this data is encoded in bytes in memory.

Constant: Data manipulated by a program that cannot be modified.

Example: SET Constant Pi to 3.141559

Variable: Data manipulated by a program that can be modified.

P a g e 12 | 65
This can be:

 Input data;
 An intermediate calculation result.
 The final result of a calculation.

Variable Declaration (with the ALGOBOX program):

AlgoBox allows the use of three types of variables: numbers (type


NUMBER), lists of numbers (type LIST), and strings (type STRING).

Syntax for Variable Declaration:

Variable VariableName : type e

Example:

Algorithm with ALGOBOX program with PASCAL

Var A : Interger

VARIABLES
Ex1 : Variable A of Integer
A
EST_DU_TYPE
NOMBRE

Identifier: Explicit name of a constant, variable, or function.

Examples: Conversion_BCD, Result, Letter...

Procedures and Functions: A procedure or function performs a


sequence of elementary actions that form a whole.

A function differs from a procedure in that it provides a result.

P a g e 13 | 65
Data Structure:
Data Structure = Organized Data + Operations on Data
Structures

Operations on Data Structures:

The following operations can be performed on data structures:

1. Traversal: Traversal allows accessing each data element


exactly once to process it.
2. Search: Search allows finding the location of a data
element if it exists in a given collection.
3. Insertion: Insertion allows adding a new data element to an
existing collection.
4. Deletion: Deletion allows removing an existing data
element from a given collection.
5. Sorting: Sorting allows organizing data elements in a
certain order:
o Ascending or descending for numeric data,
o Alphabetical or lexicographical for alphanumeric data.
6. Merging: Merging allows combining the elements of two
sorted files into a single file while maintaining the sorted order.

2. Program Organization
The algorithm of a program is organized into several parts:

 Definition of Types
 Declaration of Constants
 Declaration of Variables
P a g e 14 | 65
 Definition of Functions and Procedures
 Definition of the Main Program

2.1 Declaration of Constants

Syntax: Constant SET ConstantName to Value

Examples: Constant SET Pi: to 3.141559


Constant SET NumberLetters to 10

2.2 Declaration of Variables

Syntax: Variable SET VariableName of typeName

Examples: Variable SET Radius of Real


Variable SET Counter of Integer
Variable SET Letter of Character

2.3 Definition of the Main Program

The main program consists of a sequence of elementary operations,


often calling functions or procedures. These different operations are
mentioned using the algorithmic structures described in paragraph 5.

The main program is delimited by the keywords Begin and End.

2.4 Definition of Functions and Procedures

Procedures and functions may optionally require one or more input or


output parameters.
An input parameter is a reference to a variable manipulated by the
procedure or function.
An output parameter is a value returned by a function.
A function or procedure can itself call one or more functions and
procedures.

Syntax for Procedure Declaration:

Procedure ProcedureName (InputName1 of [Type], InputName2 of


[Type], ...)
P a g e 15 | 65
Constant ~ declaration of local constants ~
Variable ~ declaration of local variables ~
Begin
~ description of actions performed by the procedure ~
End Procedure

Syntax for Procedure Call:

ProcedureName (InputName1, InputName2...)

Syntax for Function Declaration:

Function FunctionName (InputName1: [Type], InputName2:


[Type], ...): [ResultType]
Constant ~ declaration of local constants ~
Variable ~ declaration of local variables ~
Begin
~ description of actions performed by the function ~
End Function

Syntax for Function Call:

Variable FunctionName (InputName1, InputName2...)

Examples of Function and Procedure Calls:

Procedure without
parameter: .................................................................... Ex:
Clear_Screen

Procedure with one input


parameter: ....................................................... Ex: Display ('Hello')

Function with input and output parameters: ................................ Ex:


Result SquareRoot (69)

Example of Function Declaration:

Function Average (Grade1 of Real, Grade2 of Real): Real


P a g e 16 | 65
Variable Intermediate: Real
Begin
Intermediate ← Grade1 + Grade2
Intermediate ← Intermediate / 2
Average ← Intermediate
RETURN Average
End Function

Examples of Function Use:

Display (Average(10.5, 15)) or NewGrade: Average (10, 5.15)

3. Assignment
An assignment consists of assigning a value to a variable.

The general syntax is as follows: VariableName ← Expression

"Expression" can be:

 A
constant. ......................................................................................
Ex: area ← 40
 Another variable. ......................................................... Ex: Data ←
StoredValue
 The result of a function. ................................................ Ex: result
← square (number)
 A calculation involving these different elements. ... Ex: area ← (PI
* Square (Diameter)) / 4

4. Operators - Conditions
4.1 Operators

P a g e 17 | 65
Operators allow constructing an expression to perform a calculation or
comparison.

The use of parentheses is strongly recommended for complex


expressions.

Nature Variables Associated Notati Meaning


on
Used Value
0 to 65,535 (unsigned) + Addition

Integer -32,768 to +32,767 - Subtraction


(signed)
Arithmetic
Operators 0 to 4 294 967 295 * Multiplication
Long Integer
(unsigned and signed)
Byte
0 to 255 (unsigned) / Division (real)
Single Real
1.40 x 10^-45 to 3.40 DIV Integer Division
x 10^38 (- and +)
Double Real 4.94 x 10^-324 to MOD Remainder of
1.79 x 10^308 (- and
+)
Integer Division

AND AND Function

Logical Booléen True; False OR OR Function


Operators
10 ;5 XOR Exclusive OR Function
Integer NOT Function
NOT

Concatenation String 'COURSE'; '2025'; + Concatenation


Operator 'BTS' Operator

Booléen True; False = Equal


Integer
97 ; 6 <> Different
Comparison
Operators 15 ; -20 ; 2.15 < Less Than
Single Real
'b'; '4'; 'z' > Greater Than
Character

String 'COURSE'; '2025'; 'BTS' <= Less Than or


Equal
>= Greater Than or
Equal

P a g e 18 | 65
Practical Exercise: Write an algorithm to display the values (the
number 10, pi=3.14, the letter A, the string "Hello, world") assigned to
three variables of integer, decimal, character, and string types.

program VariablesAndDataTypes;
uses crt;
uses SysUtils;

var
integerVar: Integer;
realVar: Real;
charVar: Char;
stringVar: String;

begin
ClrScr;
integerVar := 10;
realVar := 3.14;
charVar := 'A';
stringVar := 'Hello, World!';

writeln('Integer: ', integerVar);


writeln('Real: ', realVar);
writeln('Char: ', charVar);
writeln('String: ', stringVar);

ReadKey;
end.

4.2 Conditions

In the following algorithmic structures, the term "Condition" can


represent:

 A simple condition: Ex: x ≠ 0, Index ≥ 80


 A complex condition: Ex: (x > 0) AND ((y > 0) OR (z > 0)), (Index
≥ 1) AND (Index ≤ 10) ~ for 1 ≤ Index ≤ 10 ~

P a g e 19 | 65
Practical Exercise: Write an algorithm to display the result of the
sum, difference, product, quotient, and remainder of the division
between two values a and b entered from a keyboard.

program OperatorsAndExpressions;
uses crt;

var
a, b, sum, difference, product, quotient: Integer;

begin
ClrScr;
a := 10;
b := 5;

sum := a + b;
difference := a - b;
product := a * b;
quotient := a div b;

writeln('Sum: ', sum);


writeln('Difference: ', difference);
writeln('Product: ', product);
writeln('Quotient: ', quotient);

delay(10000);
end.

5. Elementary Instructions
5.1 Input Instructions

These are input instructions that allow retrieving a value entered from
an input device (keyboard, mouse, etc.). The syntax for use is as
follows:

Syntax:

READ(Identifier) or INPUT(Identifier)
The identifier is an object previously declared in the VAR section.

Example:
READ(grade1)
READ(grade2)

P a g e 20 | 65
Or

READ(grade1, grade2)
Or even
INPUT(grade1, grade2)

5.2 Output Instructions

These are display instructions that allow displaying a value on an


output device (screen).

The syntax is as follows:


WRITE(value) or DISPLAY(value)

The value of the display order can be an identifier (a variable), a


constant, an expression whose evaluation will produce a result (an
operation, a string).

Example:

WRITE('Enter the two grades')


WRITE('Enter the student's name')
WRITE(Age)
WRITE(Avg) or WRITE((grade1+grade2)/2)

Complete Example:

WRITE('Enter the student's name')


READ(StudentName)
WRITE('Enter the two grades')
READ(Grade1, Grade2)
WRITE('Enter the student's age')
READ(Age)
Avg ← (Grade1 + Grade2)/2
WRITE('The student's average: ', StudentName, ' is = ', Avg)
WRITE('The student: ', StudentName, ' is aged: ', Age, ' years')

Practical Exercise: Write an algorithm that will extract and display


the initials of a student whose name and age are entered from the
keyboard.

program InputOutputOperations;
var

P a g e 21 | 65
name: String;
age: Integer;

begin
writeln('Enter your name: ');
readln(name);
writeln('Enter your age: ');
readln(age);
writeln('Your name is ', name, ' and you are ', age, ' years old.');
end.

6. Algorithmic Structures
Algorithmic structures are divided into 3 categories:

 Linear succession of operations;


 Conditional structures or choices: depending on a condition,
the program executes different operations;
 Iterative or repetitive structures: under the control of a
condition, a sequence of operations is executed repeatedly.

6.1 Linear Sequencing

Successive actions are mentioned one after the other.

Flowchart Syntax:

Action1
Action2
...
ActionN

Note: In the following, the notation "Actions" or "ActionsN" will


represent a succession of actions as above.

Example: Calculation of a product of 2 numbers

Algorithm: productof2numbers
Step1 Start
Step2 initialize p=0 ~ product result ~
Step3 Input a, b ~ operands ~
Step4 p←a*b
Step5 Display(p)
Step6 Stop.

P a g e 22 | 65
Applied Exercise: Write the algorithm to swap the values of two
variables: Initially, a = 3 and b = 7. Subsequently, b = 3 and a
receives 7.

6.2 Choice Structures (or Conditionals)

6.2.1 IF ... THEN ... Structure

A condition is tested to determine whether the following action or


group of actions should be executed.

Flowchart Syntax:

Condition If Condition
Actions
Then Actions
EndIf

Example: Calculation of a square root

Algorithm: Calculation of a square root


Step1 Start
Step2 Initialize r = 0 ~ square root result ~
Step3 Input(x) ~ operands ~
Step4 If x > 0 Then
Step5 r ← sqrt(x)
Step6 Display(r)
Step7 EndIf
Step8 Stop.

Practical Exercise: Write the Pascal program to calculate the square


root of a value entered by the user.

6.2.2 IF ... THEN ... ELSE ... Structure

P a g e 23 | 65
A condition is tested to determine which action or group of actions
should be executed.

Flowchart Syntax:

Condition If Condition
Actions1 Actions2
Then
Actions1
Else
Actions2
EndIf

Example: Calculation of a square root of a number entered by the


user, the result must be non-signed. T.a.f: Optimize the Pascal
program.

Algorithm: Calculation of a square root of a number


Step1 Start:
Step2 Initialize r = 0 ~ square root result ~
Step3 Input(x)
Step4 If x < 0 Then
Step5 Display('x is negative')
Step6 Else
Step7 r ← sqrt(x)
Step8 Display(r)
Step9 EndIf
Step10 Stop.

Pascal Program:

program DecisionMakingStructures;

var
num: Integer;

begin
writeln('Enter a number: ');
readln(num);

P a g e 24 | 65
if num > 0 then
writeln(num, ' is positive.')
else if num < 0 then
writeln(num, ' is negative.')
else
writeln(num, ' is zero.');

end.

Application Exercise: Write the algorithm to determine if the number


entered by the user is even or odd.

Algorithm: EvenOrOdd
Variables: number: integer
Begin
Read(number)
If number % 2 = 0 Then
Display("The number is even.")
Else
Display("The number is odd.")
EndIf
End

Pascal Program:
program EvenOrOdd;
var
number: integer;
begin
writeln('Enter a number: ');
readln(number);
if number mod 2 = 0 then
writeln('The number is even.')
else
writeln('The number is odd.');
end.

Example: Algorithm to find the maximum of two numbers.

Algorithm: FindMaximum
Step1 Start
Step2 let max ~ result ~
Step3 Read(a, b)
Step4 If a > b Then
Step5 let max ← a
P a g e 25 | 65
Step6 Display('x is negative')
Step7 Else
Step8 let max ← b
Step9 EndIf
Step10 Write("The maximum is: ", max)
Step11 Stop.

Pascal Program:

program FindMaximum;

var
a, b, max: integer;

begin
writeln('Enter two numbers: ');
readln(a, b);

if a > b then
max := a
else
max := b;

writeln('The maximum is: ', max);

end.

6.2.3 Multiple Choice Structure

Data is successively compared to constant values:

Flowchart Syntax:

Data = Case Data Of


Value1
Data =
Value1 : Actions1
Value2
Value2 : Actions2
Data =
ValueN ...
Actions1 Actions2 ActionsN DefaultActions
ValueN : ActionsN

P a g e 26 | 65
Other : ActionsDéfaut
EndCase

Notes: The "DefaultActions" part may not exist. Several different


values can be grouped on the same line if the corresponding actions
are identical.

Example: Displaying the nature of a character. Write the Pascal


program corresponding to this algorithm.

Algorithm: Displaying the nature of a character


Step1 Start
Step2 Input(c)~ character entered from the keyboard ~
Step3 Case c Of
Step4 'A'..'Z': Display('Uppercase letter')
Step5 'a'..'z': Display('Lowercase letter')
Step6 '0'..'9': Display('Digit')
Step7 Other: Display('Neither letter nor
digit')
Step8 EndCase
Step9 Stop.

6.3 Iterative (or Repetitive) Structures

6.3.1 REPEAT ... UNTIL ... Structure


An action or group of actions is executed repeatedly until a condition is
met.

Flowchart Syntax:

Repeat
Actions
Actions
Until Condition
Condition

P a g e 27 | 65
Note: The condition is checked after the actions. They are therefore
executed at least once.
Example: Repetitive execution of a program
Algorithm: Repetitive execution of a program
Step1 Start:
Step2 let p0 ~ product result ~
let c of character ~ user response ~
Step3 Repeat
Step4 Read(a, b)
Step5 p←a*b
Step6 Display(p)
Step7 Write('Another calculation? No press N; Yes
any other key')
Step8 Input(c)
Step9 Until c = 'N'
Step10 Stop.

Practical Exercise: Write the algorithm for the access control


program of an authentication system.

program PINCodeChecker;
uses crt;

var
i, pin: Integer;

begin
ClrScr;
writeln('--------------------------');
writeln(' Set PIN Code: ');
writeln('--------------------------');
readln(codepin);

i := 0;

repeat
writeln('----------------------------');
writeln(' Enter your PIN Code: 🡪 ');
writeln('----------------------------');
readln(pin);
i := i + 1;
until pin = codepin;

writeln('----------------------------');
writeln(' Number of Trials: ', i);
writeln('----------------------------');

P a g e 28 | 65
delay(20000);
end.

6.3.2 WHILE ... DO ... Structure

An action or group of actions is executed repeatedly as long as a


condition is true.

Flowchart Syntax:

While Condition
Condition Do Actions
Actions EndDo

Note: The condition is checked before the actions. They may


therefore never be executed.

Example: Repetitive execution of an action

Begin
While Not (KeyPressed)
Do
Display('Waiting')
EndDo
End

Practical Exercise: Write the counting algorithm from 1 to 10.

program Counting;
uses crt;
uses SysUtils;

var
i: Integer;

begin
ClrScr;
i := 1;

P a g e 29 | 65
while i <= 10 do
begin
writeln('While loop iteration: ', i);
i := i + 1;
end;

delay(15000);
end.

6.3.3 FOR Index FROM ... TO ... DO ... Structure

An action or group of actions is executed repeatedly a certain number


of times: the number depends on the initial and final values given to
the variable "Index".

Flowchart Syntax:

For Index From Value1 To Value2


Do
Actions
EndDo

Note: The initial (Value1) and final (Value2) values are included.

It is optionally possible to specify a different increment step (+2, +10, -


1, etc.)

Example: Displaying a line of stars

Variable:
i: integer ~ loop counter ~
Begin
For i From 1 To 80
Do
Display('*')
EndDo
End

Application Exercise: Write an algorithm that will input an integer N


(N >= 0) and then calculate and display the factorial of N, with N! = N
* (N-1) * (N-2) * ... * (N-n).

P a g e 30 | 65
program CalculateFactorial;

var
n, i, factorial: integer;

begin
writeln('Enter a number: ');
readln(n);

factorial := 1;

for i := 1 to n do
factorial := factorial * i;

writeln('The factorial is: ', factorial);


end.

Application Exercise: Algorithm that calculates the multiplication


table from 1 to 12.

program MultiTables;
uses crt;
uses SysUtils;

var
i, j: Integer;

begin
ClrScr;

for i := 1 to 12 do
begin
writeln('Multiplication Table: ', i);
writeln('------------------------');

for j := 1 to 10 do
begin
writeln(i, 'x', j, '=', i*j);
j := j + 1;
end;

Inc(i);
end;

delay(15000);
end.
Inc Inc
Loop 2 j j . . J
1 2
. . 1
i
0
1
Loop 1
..
..
..
I
P a g e 31 | 65

2
Note: This algorithmic structure can actually be replaced by a
WHILE ... DO ... structure.

1. Start
2. Let i ← 1~ loop counter ~
3. While i ≤ 80
4. Do
5. Display('*')
6. i ← i + 1 ~ Increment by 1 ~
7. EndDo
8. End

6.4 Accumulators and Counters

6.4.1 Accumulators or Totalizers

These are cumulative variables that successively receive the content


of another variable of the same type from a starting position to the end
of the specified processing (final state).

The syntax is as follows:

Identifier Identifier + variable

(Final State) (Initial State) (Cumulative Content)

Example: Suppose we need to calculate the total payments made by


a student for their tuition to determine their solvency status. The
variables to declare can be as follows:

 Pay: variable for entering different payments


 TotalPay: variable for accumulating different payments made

TotalPay Count
Payment Number Pay Initial Final Initial Fin
al

1st payment 100, 000 0 100, 000 0 1

P a g e 32 | 65
2nd payment 50, 000 100, 150, 000 1 2
000

3rd payment 75, 000 150, 225, 000 2 3


000

TotalPay 
TotalPay + Pay

6.4.2 Counters

These are variables that calculate and determine the number of times
an action or processing is executed during processing. Counters evolve
according to a step.

We speak of incrementation when the counter variable evolves


progressively according to the step and decrementation when it
decreases according to the step.

The syntax is as follows:

Identifier  Identifier + or - step

(Final State) (Initial State) (Incrementation or Decrementation)

Note: The default step is equal to 1, but depending on the required


processing, it can have a value greater than 1.

Example:

Considering that a student can make several payments for their


tuition, to calculate the number of payments made by the student, a
counter variable must be declared that will evaluate from a starting
position to a final position according to the step (1).

Count  Count
+1

Note: Variables (TotalPay and Count) must be declared beforehand in


the VAR section and initialized to a starting value before being used in
calculation instructions. Example (initialization): In our case,

TotalPay ← 0
P a g e 33 | 65
Count ← 0

7. Subprograms

When a program is long, it is not advisable to write its code entirely. It


should be divided into several smaller parts that are assembled to form
the final application. Subprograms (procedures and functions) thus
allow breaking down a large program into simpler parts that are easier
to code and understand, thereby avoiding the repetition of identical
codes.

Like a program, a subprogram has a name, variables, instructions,


a beginning, and an end. But unlike a program, a subprogram cannot
execute independently of another program.

The execution of a subprogram is requested by the main program (or


another subprogram) using a specific instruction called CALL.

The main program is therefore the set that executes when the
application is launched and is responsible for requesting the execution
of the instructions in the subprogram.

7.1 Functions

A function returns a value.

Role of Functions:

 Reusability: Avoids code repetition.


 Modularity: Divides the program into simple tasks.
 Clarity: Makes the code more readable and maintainable.

Practical Example: Write a function to calculate the sum of two


numbers.

Algorithm:

Function Sum(a, b: integer): integer


Variable a,b of integer
Begin
result = a + b
Return: result
End Function

P a g e 34 | 65
Pascal Program:

program SumFunction;

{
This program uses a function to calculate the sum of two numbers.
It shows how to declare, define, and call a function in Pascal.
}

var
num1, num2, result: integer; { Variables to store numbers and result }

{ Declaration of the Sum function }

function Sum(a, b: integer): integer;


{
This function takes two integers as input and returns their sum.
Parameters: a, b: the two numbers to add
Returns: The sum of a and b
}

begin
Sum := a + b; { Calculates the sum and returns it }
end;

begin
writeln('Enter two numbers:'); { Asks the user to enter two numbers }
readln(num1, num2); { Reads the two numbers }
result := Sum(num1, num2); { Calls the Sum function and stores the result }
writeln('The sum is: ', result); { Displays the result }
end.

7.2 Dynamic Programming

Role of Dynamic Programming:

 Avoids recalculations: Stores results for later reuse.


 Optimization: Reduces the time complexity of certain
algorithms.

7.2.1 Recursive Function of the Factorial of a Positive Integer

Recursion allows performing repetitive processing. Unlike repetitive


control structures (loops), recursion is used when the definition of a
concept refers to the same concept.

Recursion, called recurrence in mathematics, allows performing


particularly complex repetitive processing that classic iterative
structures cannot easily handle.

P a g e 35 | 65
Application of Recursion:

The factorial of a positive integer N is equal to the product of this


number by all the positive integers less than it:

Factorial(N) = N * (N-1) * (N-2) * ... * 2 * 1

According to the postulate:


Factorial(0) = 1
Fact(N) = 1 if N = 0
Fact(N) = N * Fact(N-1) otherwise.

Execution:

Fact(3) = 3 * Fact(2) = 3 * 2 * Fact(1) = 3 * 2 * 1 * Fact(0) = 3 * 2 * 1 *


1 = 6.

1. Function Fact(N: integer): integer


2. Begin
3. If N = 0 Then
4. Fact ← 1
5. Else
6. Fact ← N * Fact(N-1)
7. EndIf
8. Return Fact
9. End Function

Example: Write an algorithm, given the values of M and N, that


calculates the combination:

Algorithm Solution:

Algorithm Combination
Start
let m, n as byte
let Comb as integer
Procedure Factorial(X: byte, Fact: integer): integer
let i as byte
Begin
If (X = 1) or (X = 0) Then
Fact ← 1
P a g e 36 | 65
Else
Fact ← 1
For i ← 1 to X Do
Fact ← Fact * i
EndFor i
EndIf
End Procedure

Read m, n
If (m >= n) and (n >= 1) Then
Comb ← Factorial(m, 1) / Factorial(n, 1) * Factorial(m-
n, 1)
Write Comb
EndIf
END.

Pascal Solution:

Program Combination;

Var i, Fact: integer;

Function Factorial(n: integer): integer;

Begin
Fact := 1;
For I := 1 to n Do
Factorial := Fact;
End;

Begin
Write('Enter two integers m and n');
Readln(m, n);
Write(Factorial(m) / Factorial(n) * Factorial(m-n));
End.

7.2.2 Recursive Function of the Fibonacci Sequence

Concept: Solve a problem by breaking it down into sub-problems


and storing intermediate results.

Simple Explanation of the Fibonacci Sequence

 What is the Fibonacci Sequence?


The Fibonacci sequence is a series of numbers where each number
is the sum of the two preceding ones. It usually starts with 0 and
1.

Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...


P a g e 37 | 65
 0 (first term)
 1 (second term)
 1 (0 + 1)
 2 (1 + 1)
 3 (1 + 2)
 5 (2 + 3)
 8 (3 + 5)
 And so on...

What is the Fibonacci Sequence Used For?

The Fibonacci sequence appears in many natural and mathematical


phenomena:

 Nature: Arrangement of leaves on a stem, spirals of shells,


arrangement of sunflower seeds.
 Computer Science: Sorting algorithms, data structures,
optimization.
 Finance: Growth models, economic forecasts.
 Art and Architecture: Aesthetic proportions (golden ratio).
 How to Calculate a Fibonacci Number?

To find the nth Fibonacci number, use the following recursive


formula:

 F(0) = 0
 F(1) = 1
 F(n) = F(n-1) + F(n-2) for n > 1

Example:

 F(2) = F(1) + F(0) = 1 + 0 = 1


 F(3) = F(2) + F(1) = 1 + 1 = 2
 F(4) = F(3) + F(2) = 2 + 1 = 3
 F(5) = F(4) + F(3) = 3 + 2 = 5

Exercise: Calculate the Fibonacci sequence.

Write a recursive function that takes an integer n as input and


calculates the function f defined by:

F(n) = 1, if n < 0 and n < 2

F(n) = 1 + f(n-1) + 2 * f(n-2) if n < 2


P a g e 38 | 65
Algorithm:

Algorithm Fibonacci(n: integer): integer


Process:
1. If n <= 1 Then
Return: n
2. Else
Return: Fibonacci(n-1) + Fibonacci(n-2)
End Algorithm

Pascal Program (with memoization):

program DynamicFibonacci;

{
This program calculates the Fibonacci sequence with dynamic programming.
It shows how to use memoization to avoid unnecessary recalculations.
}

const
MAX = 100; { Maximum size of the memoization table }

var
memo: array[0..MAX] of integer; { Table to store intermediate results }
n: integer; { Number for which we want to calculate the Fibonacci sequence }

{ Recursive function with memoization to calculate Fibonacci }

function Fibonacci(n: integer): integer;

begin
{ If the result is already calculated, return it directly }
if memo[n] <> -1 then
Fibonacci := memo[n]
{ Base case: Fibonacci(0) = 0 and Fibonacci(1) = 1 }
else if n <= 1 then
Fibonacci := n
{ Recursive case: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2) }
else
begin
memo[n] := Fibonacci(n-1) + Fibonacci(n-2); { Store the result in the table }
Fibonacci := memo[n]; { Return the result }
end;
end;

begin
{ Initialize the memoization table with -1 (not calculated) }
for n := 0 to MAX do
memo[n] := -1;

P a g e 39 | 65
writeln('Enter a number:');
readln(n); { Read the number }
writeln('Fibonacci(', n, ') = ', Fibonacci(n)); { Display the result }
end.

7.3 Procedures

A procedure does not have a return value.

Role of Procedures:

 Encapsulation: Groups actions without returning a result.


 Organization: Structures the code into logical tasks.
 Flexibility: Allows modifying behavior without changing the rest
of the program.

Practical Example: Write a procedure to display a welcome message.

Algorithm:

Procedure WelcomeMessage(name: string)


Process:
Output: "Hello, " + name + "!"
End Procedure

Pascal Program:

program WelcomeProcedure;

{
This program uses a procedure to display a welcome message.
It shows how to declare, define, and call a procedure in Pascal.
}

var
userName: string; { Variable to store the user's name }

{ Declaration of the WelcomeMessage procedure }

P a g e 40 | 65
procedure WelcomeMessage(name: string);
{
This procedure displays a personalized welcome message.
Parameters: name: the name of the person to greet
}

begin
writeln('Hello, ', name, '!'); { Displays the welcome message }
end;

begin
writeln('Enter your name:'); { Asks the user to enter their name }
readln(userName); { Reads the name }
WelcomeMessage(userName); { Calls the WelcomeMessage procedure }
end.

PRACTICAL EXERCISES
Exercise 1:

Write an algorithm to display the multiplication table by 9 from 1 to 10.

Exercise 2:

Write an algorithm that will input a word with a maximum of 10


characters and then calculate and display the number of vowels in the
word.

Synthesis Exercise:

Exercise 1: Write an algorithm to display the multiplication tables


from 1 to 10. Each table goes from 1 to 12.

Exercise 2: Write an algorithm that will input an integer N (N >= 0)


and then calculate and display the factorial of N, with N! = N * (N-1) *
(N-2) * ... * (N-n).

Exercise 3: Write an algorithm that will input two integers N and P,


with (N > 0) and (P >= 0), and then calculate and display the result of
N^P.

P a g e 41 | 65
CHAPTER 4: Arrays and Linear Data
Structures
I. ARRAYS

Simply put, arrays are reserved areas in RAM (Random Access


Memory) intended for storing grouped information used
linearly in processing. More elaborately, an array is a linear data
structure that allows storing data of the same type in reserved
areas of RAM. Each stored value is detected by an index that
indicates the position of the data in the array.

1. The Notion of Index

Indices are pointers that allow locating the different cells of an array
to facilitate its exploitation. The index is characterized by the following
elements:

 A name
 A starting value (initial value)
 A final value: it determines the size of the array, i.e., the number
of cells
 Its type

The index of an array can be a constant or a variable of integer type.


P a g e 42 | 65
2. Array Declaration

The array is declared as a particular type of data with the following


elements:

 A name
 A minimum index value
 A maximum index value (array size)
 The type of data stored in the array.

The declaration syntax is as follows:

a) First Method:

VAR array_name [min_index..max_index] ARRAY OF data_type

b) Second Method:

TYPE array_type_name [min_index..max_index] ARRAY OF data_type

VAR array_name: array_type_name

The min and max indices are integer values.

The data type can be: integer, real, character, string.

Example: The averages of 10 students in a class are stored in an


array as:

 VAR Averages [1..10]: ARRAY OF real

or

 TYPE TAB Avg [1..10]: OF real


VAR Averages: TAB Avg

P a g e 43 | 65
II. ONE-DIMENSIONAL ARRAYS

One-dimensional arrays or vectors: dim1

These are arrays that use only one index for their exploitation. In this
case, the processing is done linearly in the horizontal or vertical
direction.

A vector or dim1 array is a finite sequence of elements of the same


type indexed over an interval of a finite and ordered type that can be
predefined or defined in the algorithm.

1. Creating a One-Dimensional Array

This is an operation that consists of filling the contents of the different


cells that make it up with values of the same type as the one declared.

Algorithm creation1

start
let averages [1..10]: ARRAY OF real
let i of integer
For i From 1 To 10 Do
Write('Enter The Average Of Student: ', i)
Read(Averages[i])
i←i+1
End For
End.

Role of Arrays:

 Collection Storage: Allows managing multiple values of the


same type.
 Fast Access: Elements are accessible via an index.

Exercise: Calculate the sum of the elements of an array of 5 integers.

Algorithm:

Algorithm SumArray

Input: array[1..5] (integer)

Process:

P a g e 44 | 65
1. sum = 0
2. For i = 1 to 5 Do sum = sum + array[i] Output: sum

End Algorithm

Pascal Program:

program SumArray;

{
This program calculates the sum of the elements of an array.
It shows how to declare, fill, and traverse an array in Pascal.
}

var
array: array[1..5] of integer; { Declaration of an array of 5 integers }
i, sum: integer; { Variables for index and sum }

begin
{ Filling the array }
for i := 1 to 5 do
begin
writeln('Enter element ', i, ':');
readln(array[i]); { Reads each element of the array }
end;

{ Calculating the sum }


sum := 0; { Initializes the sum to 0 }
for i := 1 to 5 do
sum := sum + array[i]; { Adds each element to the sum }

writeln('The sum is: ', sum); { Displays the sum }


end.

a. Different Operations in a One-Dimensional Array

Several types of processing can be performed on the data structure of


a one-dimensional array, such as:

 Sum
 Product
 Average of cells
 Search for minimum and maximum
 Sorting array values
 Deleting an element

Sum of Array Elements

P a g e 45 | 65
Algorithm:

1. Initialize a sum variable to 0.


2. Traverse each element of the array.
3. Add each element to sum.
4. Display sum.

Pascal Program:

program SumArray;

var
tab: array[1..5] of integer; // Array of 5 integers
i, sum: integer;

begin
// Initializing the array
tab[1] := 10;
tab[2] := 20;
tab[3] := 30;
tab[4] := 40;
tab[5] := 50;

sum := 0; // Initializing the sum

// Calculating the sum


for i := 1 to 5 do
sum := sum + tab[i];

// Displaying the result


writeln('The sum of the array elements is: ', sum);
end.

Product of Array Elements

Algorithm:

1. Initialize a product variable to 1.


2. Traverse each element of the array.
3. Multiply each element with product.
4. Display product.

Pascal Program:

program ProductArray;

P a g e 46 | 65
var
tab: array[1..5] of integer;
i, product: integer;

begin
// Initializing the array
tab[1] := 2;
tab[2] := 3;
tab[3] := 4;
tab[4] := 5;
tab[5] := 6;

product := 1; // Initializing the product

// Calculating the product


for i := 1 to 5 do
product := product * tab[i];

// Displaying the result


writeln('The product of the array elements is: ', product);
end.

Average of Array Elements

Algorithm:

1. Calculate the sum of the elements (as above).


2. Divide the sum by the number of elements.
3. Display the average.

Pascal Program:

program AverageArray;

P a g e 47 | 65
var
tab: array[1..5] of integer;
i, sum, average: integer;

begin
// Initializing the array
tab[1] := 10;
tab[2] := 20;
tab[3] := 30;
tab[4] := 40;
tab[5] := 50;

sum := 0; // Initializing the sum

// Calculating the sum


for i := 1 to 5 do
sum := sum + tab[i];

average := sum div 5; // Calculating the average

// Displaying the result


writeln('The average of the array elements is: ', average);
end.

Search for Minimum and Maximum

Algorithm:

1. Initialize min and max with the first element of the array.
2. Traverse each element of the array.
3. If an element is smaller than min, update min.
4. If an element is larger than max, update max.
5. Display min and max.

P a g e 48 | 65
Pascal Program:

program MinMaxArray;

var
tab: array[1..5] of integer;
i, min, max: integer;

begin
// Initializing the array
tab[1] := 15;
tab[2] := 7;
tab[3] := 22;
tab[4] := 3;
tab[5] := 19;

min := tab[1]; // Initializing min


max := tab[1]; // Initializing max

// Searching for min and max


for i := 2 to 5 do
begin
if tab[i] < min then
min := tab[i];
if tab[i] > max then
max := tab[i];
end;

// Displaying the results


writeln('The minimum is: ', min);
writeln('The maximum is: ', max);
end.

Sorting Array Values (in Ascending Order)

Algorithm (Selection Sort):

1. Traverse the array from the first to the second-to-last cell.


2. For each cell, find the smallest element in the rest of the array.
3. Swap this element with the current cell.
4. Display the sorted array.
P a g e 49 | 65
Pascal Program:

program SortArray;

var
tab: array[1..5] of integer;
i, j, temp, minIndex: integer;

begin
// Initializing the array
tab[1] := 22;
tab[2] := 7;
tab[3] := 15;
tab[4] := 3;
tab[5] := 19;

// Selection sort
for i := 1 to 4 do
begin
minIndex := i;
for j := i + 1 to 5 do
if tab[j] < tab[minIndex] then
minIndex := j;

// Swapping elements
temp := tab[i];
tab[i] := tab[minIndex];
tab[minIndex] := temp;
end;

// Displaying the sorted array


writeln('Sorted array:');
for i := 1 to 5 do
write(tab[i], ' ');
end.

Bubble Sort

Exercise: Sort an array of 5 integers using bubble sort.

Role of Bubble Sort:

 Simplicity: Easy to understand and implement.

P a g e 50 | 65
 Educational: Good for learning the basics of sorting algorithms.

Algorithm:

Algorithm BubbleSort

Input: array[1..5] (integer)

Process:

1. For i = 1 to 4 Do For j = 1 to 5-i Do If array[j] > array[j+1] Then


Swap(array[j], array[j+1])

End Algorithm

Pascal Program:

program BubbleSort;

{
This program sorts an array using bubble sort.
It shows how to implement a simple sorting algorithm.
}

var
array: array[1..5] of integer; { Array to sort }
i, j, temp: integer; { Variables for loops and swapping }

begin
{ Reading array elements }
for i := 1 to 5 do
begin
writeln('Enter element ', i, ':');
readln(array[i]);
end;

{ Bubble sort }
for i := 1 to 4 do { Traverse the array }
for j := 1 to 5-i do { Compare adjacent elements }
if array[j] > array[j+1] then { If the current element is greater than the next }
begin
{ Swap elements }
temp := array[j];
array[j] := array[j+1];
array[j+1] := temp;
end;

{ Displaying the sorted array }


writeln('Sorted array:');
for i := 1 to 5 do
write(array[i], ' ');
end.
P a g e 51 | 65
Deleting an Element

Algorithm:

1. Ask the user for the position of the element to delete.


2. Shift all elements after this position one place to the left.
3. Reduce the array size by 1.

Pascal Program:

program DeleteElement;

var
tab: array[1..5] of integer;
i, pos: integer;

begin
// Initializing the array
tab[1] := 10;
tab[2] := 20;
tab[3] := 30;
tab[4] := 40;
tab[5] := 50;

writeln('Enter the position of the element to delete (1 to 5): ');


readln(pos);

// Shifting elements
for i := pos to 4 do
tab[i] := tab[i + 1];

// Displaying the array after deletion


writeln('Array after deletion:');
for i := 1 to 4 do
write(tab[i], ' ');
end.

III. TWO-DIMENSIONAL ARRAYS

Exercise: Display the elements of a 2x2 array.

Role of 2D Arrays:

P a g e 52 | 65
 Matrix Representation: Useful for mathematical calculations
and grids.
 Data Organization: Allows structuring data in rows and
columns.

Algorithm:

Algorithm Print2DArray

Input: array[1..2, 1..2] (integer)

Process:

1. For i = 1 to 2 Do For j = 1 to 2 Do Output: array[i, j]

End Algorithm

Pascal Program:

program Print2DArray;

{
This program displays the elements of a 2D array.
It shows how to declare, fill, and traverse a two-dimensional array.
}

var
array: array[1..2, 1..2] of integer; { Declaration of a 2x2 2D array }
i, j: integer; { Variables for indices }

begin
{ Filling the 2D array }
for i := 1 to 2 do
for j := 1 to 2 do
begin
writeln('Enter element [', i, ',', j, ']:');
readln(array[i, j]); { Reads each element of the array }
end;

{ Displaying the 2D array }


for i := 1 to 2 do
begin
for j := 1 to 2 do
write(array[i, j], ' '); { Displays each element }
writeln; { Moves to the next line after each row of the array }
end;
end.

IV. STRUCTURE TYPES AND RECORDS

P a g e 53 | 65
1. Variables and Data Types

Role of Variables:

 Temporary Storage: Allows manipulating data in memory.


 Strong Typing: Pascal enforces strict typing, which reduces
errors.

Pascal supports several data types:

Integer (integers), Real (decimal numbers), Char (characters), String


(strings), Boolean (true/false).

Unlike arrays, which are data structures where all elements are
of the same type, records are data structures where elements
can be of different types and relate to the same entity. The
elements that make up a record are called fields.

Example: Suppose the following problem:

We want to calculate and display the averages of two grades (TD and
TP) obtained by students in a program. We also want to memorize the
name and first name of each student in a class of 20 students.

How to memorize and manipulate this data of different types?

Solution 1:

Use multiple arrays


CONST nbre = 20
VAR
Name [1..Nbre]: ARRAY OF STRING
FirstName [1..Nbre]: ARRAY OF STRING
TD [1..Nbre]: ARRAY OF REAL
TP [1..Nbre]: ARRAY OF REAL

 The disadvantage in this case is the manipulation of several


arrays, each containing data of a specific type.

Solution 2:

 Use a single array that integrates the different data types since
each student is characterized by a name, a first name, a TD
grade, and a TP grade. Hence the concept of a record.

P a g e 54 | 65
Field1 Field2 Field3 Field4 Field1 Field2 Field3 Field4
Type1 Type2 Type3 Type4 Type1 Type2 Type3 Type4
1st record 2nd record

Example: S.C: string

Name FirstNa SPW PE Name FirstNa SPW PE


S.C me S.C Real S.C me S.C Real
Real Real
1st record 2nd record

Declaration of a Structured Type

Apart from classic types (real, integer, string, boolean), it is possible to


create your own types and then declare variables or arrays of elements
of this type. In this case, you must declare a new type based on
another existing type, and variables of this structured type are called
records.

The syntax is as follows:

TYPE <TypeName> = RECORD


Field1: type1
Field2: type2
..............
Fieldn: type n
END RECORD

NB: type1, type2, ..., type n can be different.

P a g e 55 | 65
Example:

TYPE STUDENTS = RECORD


Name: string
FirstName: string
TD, TP: Real
END RECORD

To use a record type (Structured), you must declare a variable of this


type in the VAR section.

Example:

TYPE STUDENTS = RECORD


Name, FirstName: string
TD, TP: Real
END RECORD

VAR Student: STUDENTS

Records are composed of several data areas corresponding to the


fields. Manipulating a record is done through its fields, and to display a
record, you must display the values of all its fields one by one.

Unlike arrays (accessed by index), the fields of a record are accessible


through their names and the dot operator "."

The access syntax is as follows:

<variable_name.field>

Example:

Student.Name
Student.FirstName
Student.TD
Student.TP

P a g e 56 | 65
Exercise: Declare a variable to store the name, age, and height of 4
students.

Pascal Program:

program SimpleStudentRecord;
uses crt;

type
Student = Record
name: String[50];
average: Real;
age: Integer;
end;

var
students: array[1..4] of Student;
i: Integer;

begin
ClrScr;

for i := 1 to 4 do
begin
write('Enter student name ', i, ': ');
readln(students[i].name);
write('Enter student age ', i, ': ');
readln(students[i].age);
write('Enter student average ', i, ': ');
readln(students[i].average);
end;

// Display student information


writeln('STUDENT INFORMATION');
for i := 1 to 4 do
begin
writeln('Student ', i, ':');
writeln('Name: ', students[i].name);
writeln('Age: ', students[i].age);
writeln('Average: ', students[i].average:0:2);
end;

readkey;
end.

P a g e 57 | 65
V. FILE STRUCTURES

1. Introduction

Data structures such as arrays, indices, records, and pointers


are stored in RAM. That is, in the volatile area of the machine where
the lifetime of a variable is equal to the execution time of the
associated program. This solution is not feasible for the
computerization of a company or organization.

Data concerning a student, a product, or an order must be stored


longer than the duration of the program. Therefore, the processed
values must be copied to a non-volatile medium (physical medium)
such as: hard disk, magnetic tape, magnetic cassette, USB key, etc.

In addition to the instructions that allow exchanging values between


the user and the machine using an output device (screen) and an input
device (keyboard), those that allow exchanges between the central
memory and the physical medium will be used, such as (read, write,
rewrite, consult, modify, delete).

The information on a physical medium must be grouped together


based on the characterized entity, hence the concept of a file.

2. Definition

Record: A collection of stored data defining the entity being processed


completely. A record is the combination of values taken by each
attribute of a file.

File: A set of records stored on a physical medium with a name and


defining the same entity or object.

3. File Organization

This organization refers to the method of implementing data and


records in the file based on access properties. There are generally two
types of file organization.

P a g e 58 | 65
a. Sequential Organization

In this case, all records in the file are traversed from the first to the
last, one after the other. That is, to access the data of order N, you
must first traverse the previous N-1 data. This is also called linear
organization.

b. Relative or Indexed Organization

In this case, records are identified by an order number or index


number, and access to data is independent of the previous ones and is
done through the index.

4. Different Types of Data Access

In practice, access types are related to file organization types. It is the


method used to access data in a file (while organization defines the
implementation of data in a file). There are two methods for accessing
data in a file.

 Sequential access
 Direct access

Note: The type of access to file data is determined based on the


program's objectives, the type of medium, and the volume of data.

5. Sequential Access Files

a. Definition

A file is said to have sequential access if accessing its nth index record
requires going through the previous n-1 records. In this case, records
are written one after the other, and reading always starts with the first,
then the next, until the last.

b. Description of Some Instructions Used in Sequential


Files

Example: Suppose we have stored the names and birth years of


students in a class on a medium.

| EDIMO | 1990 | ONANA | 1997 | KAMDEN | 1998 | ZEBAZE | 1995 | ...


| ... |

P a g e 59 | 65
 Read Instruction:

READ STUDENT copies data from the physical medium to the central
memory, the information of a student based on two previously
declared variables that must receive the read data (NameS, BirthY).

 Write Instruction:

WRITE STUDENT copies data from central memory to a free block on


the physical medium.

 Rewrite Instruction:

REWRITE STUDENT recopies data from central memory in place of


the last linked data.

 Delete Instruction:

DELETE STUDENT updates an indicator in front of the last linked data


to logically indicate that they should no longer be processed: This is
called logical deletion.

Physical deletion consists of shifting to the left and from a position in


the medium all subsequent data.

c. File Declaration

A file can be declared in two ways:

 As a particular file type


 As a file variable of a record type

First Method:

TYPE record_type_name = RECORD


Field1: type1
Field2: type2
Fieldn: type n
END RECORD

VAR record_variable_name = record_type_name


File_Name: FILE OF record_type_name

Second Method:
P a g e 60 | 65
TYPE file_type_name = FILE
Record_Type_Name = RECORD
Field1: type1
Field2: type2
Fieldn: type n
END RECORD

VAR record_variable_name: record_type_name


File_Name: file_type_name

Processing Applied to Files

Description Algorithmic Syntax


Before using a file, you must ASSOCIATE (logical name,
ASSOCIATE its logical name physical name) or ASSIGN (logical
with its physical name name, physical name)
If the file exists: OPEN the
file and erase its content. If
RECREATE (logical name)
the file does not exist:
CREATE the file
OPEN an existing file (create) and
reposition or reset its pointer to 0.
Indicate if the file will be:
- Read (L) OPEN (logical name)
- Written (E)
- Updated (L/E)
WRITE (E) or modify a value or WRITE (logical name; record
record in the file variable name)
READ (L) a value or record from a READ (logical name, record

P a g e 61 | 65
file variable name)
CLOSE a file (always do this when | CLOSE (logical name)
it has been opened)
Boolean test function to check if IF End_OF_FILE (logical name)
the end of the file is reached Then action1
Else action2
ENDIF

Note:

 The physical name of a file or external name or file label is the


one that allows identifying it on the physical medium.
 The logical name of a file or internal name is the name of the file
variable (declared under the file type) and used in the program's
instructions.
 The WRITE and READ instructions do not concern the file
globally but one of its records.
 Reading requires a test because sequential readings end when
all records have been read one by one; in this case, a boolean
indicator of the file management system (END OF FILE) allows
identifying that there are no more records to read.
 The DELETE and REWRITE instructions are executed only after
reading.

TYPE list = ^element.

Simple Algorithm

Objective:

Write text to a file, then read it back and display it on the screen.

Steps:

1. Open a file for writing.


2. Write a line of text to the file.
3. Close the file.
4. Reopen the file for reading.
5. Read the content and display it.
6. Close the file.
P a g e 62 | 65
Corresponding Pascal Program

program SimpleFileManagement;

var
MyFile: text; // Variable to manipulate the file
TextToRead: string; // Variable to store the read text

begin
{ Step 1: Opening the file for writing }
assign(MyFile, 'myfile.txt');
rewrite(MyFile);

{ Step 2: Writing to the file }


writeln(MyFile, 'Hello, I am a line in a file!');

{ Step 3: Closing the file after writing }


close(MyFile);

{ Step 4: Reopening the file for reading }


reset(MyFile);

{ Step 5: Reading the content and displaying it }


while not eof(MyFile) do
begin
readln(MyFile, TextToRead);
writeln('File content: ', TextToRead);
end;

{ Step 6: Closing the file after reading }


close(MyFile);
end.

Step-by-Step Explanations

1. Declaration:

 MyFile is a variable of type text to manipulate the file.


 TextToRead stores each line read.

2. Opening for Writing:

 assign(MyFile, 'myfile.txt'): Associates the physical file name with


the variable.
 rewrite(MyFile): Opens the file in write mode (creates the file if it
does not exist, otherwise overwrites it).

3. Writing:

P a g e 63 | 65
 writeln(MyFile, 'Hello...'): Writes a line to the file.

4. Closing:
 close(MyFile): Closes the file after writing.

5. Opening for Reading:

 reset(MyFile): Opens the file in read mode.

6. Reading and Displaying:

 while not eof(MyFile) do: Loops until the end of the file.
 readln(MyFile, TextToRead): Reads a line from the file.
 writeln('File content: ', TextToRead): Displays the line read.

7. Final Closing:

 close(MyFile): Closes the file after reading.

4. Expected Result:

 A file named myfile.txt will be created in the same folder as


your program.
 It will contain the line: Hello, I am a line in a file!
 The program will display this line on the screen after reading it.

5. Tips for Beginners:

 Check the file location: After execution, look for myfile.txt in


the program folder.
 Modify the text: Try writing multiple lines with multiple writeln.
 Error handling: To go further, you can add a test with IOResult
to check if the file opens correctly.

P a g e 64 | 65

You might also like