Professional Documents
Culture Documents
Algo Course
Algo Course
Houcemeddine FILALI
1 Introduction
2 Simple operations
3 Simple Types
4 Flow-control structures
6 Modular Programming
Chapter 0 : Algorithmic concepts
Introduction
Plan
1 Introduction
Algorithms
Data
Processing
Basic Concepts
Computer Science
Computer science is a scientific, technical, and industrial field
related to the automatic processing of information through the
execution of computer programs by machines: embedded systems,
computers, robots, automata, etc. [Wikipedia]
Information
Information refers to both the message to be communicated and
the symbols used to write it; it uses a code of meaningful signs
such as an alphabet of letters, a set of numbers, ideograms, or
pictograms. [Wikipedia]
Algorithmics
Algorithm
Origin: Arabic.
Description: A precise description, in the form of simple
concepts, of how to solve a problem. It can be compared to a
cooking recipe, a machine user manual, or directions to reach
a destination.
In the context of computing: An algorithm is a finite
sequence of instructions. The sequential execution of these
instructions transforms the input data to solve a
computational problem.
Structure of an algorithm
Algorithm Structure
Algorithm [Title]
const [Declaration of Constants]
type [Declaration of New Types]
var [Declaration of Variables] Declaration of Constants
Begin ConstantIdentifier1 = ConstantValue1
.
Instruction1 .
Instruction2 .
ConstantIdentifierK = ConstantValueK
.
.
.
InstructionN
End Declaration of New Types
Example TypeIdentifier1 = TypeDeclaration1
.
Algorithm A const T = 100 .
.
type Tab: Array[1..T ] of real
TypeIdentifierK = TypeDeclarationK
var X , Y : Tab
N, i: integer
Begin
Declaration of Variables
Write("Enter the size of the array: ") VarId11 , . . ., VarId1K : Type1
Read(N)
for i from 1 to N do .
.
X [i] ← i .
Y [i] ← X [i] + 1 VarIdN1 , . . ., VarIdNK : TypeN
end
End
Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 6 / 57
Chapter 0 : Algorithmic concepts
Introduction
Data
Identifier
Identifier
An identifier is a name created by the programmer to refer to an
object. This name must start with an alphabetic letter or an
underscore (_) followed by a combination of letters, digits, and
underscores.
Caution
Some keywords {Algorithm, Const, Var, Begin, End, . . .} are
reserved and cannot be used as identifiers under any circum-
stances.
Constant
Definition
A constant is an object whose value remains fixed throughout the execution of a program. There are
two types of constants:
Literal Constants: directly designated by their values.
Numeric Constants: 5, 3.2, -1, etc.
Boolean Constants: True, False.
Character Constants: 'a', '+', ' ', '@', etc.
String Constants: "med ali", "Python", etc.
Named Constants: declared in the Const clause and designated by an identifier.
Caution
A constant should never appear:
On the left side of an assignment: Const ← Value
As an output parameter when calling a subprogram: Read(Const)
Variable
Variable Definition
A variable is an object whose value can change throughout the execution
of an algorithm. A variable is characterized by:
An Identifier : A unique name to refer to its content.
An Address : The memory location where this variable is stored.
A Type : Indicating the set of values and operations compatible
with the variable.
A Scope : The portion of the code where this variable is visible
(local, global).
Caution
A variable must be initialized before it is used in an expression.
Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 9 / 57
Chapter 0 : Algorithmic concepts
Introduction
Data
Type
Type
There are two families of types:
Simple Types (Primitives) : Boolean, Integer, Real, and
Character.
Composite Types (Containers/ Iterables): Strings and Arrays.
The type of a variable determines:
The set of values that can be assigned to it.
The set of operations that can be applied to it.
Instruction
Instruction
An instruction occupies an entire line in an algorithm and can
contain:
An assignment of an expression to a variable.
A procedure call, passing expressions as inputs to it.
Examples of Instructions
X ←1
Y ←X ∗3+X ∗X
Write(X , Y , X ∗ Y + 2 ∗ Y )
Read(X )
Expression
Expression
An expression is a composition of operators (simple operators, function calls) and operands. An
expression has a type, which is the type of the result obtained when evaluating it.
Operator
An operator symbolizes an action and is characterized by:
Arity: The number of operands it requires.
Priority: The order of its evaluation when it appears in a composed expression.
Type of compatible operands.
Operand
An operand is an object (constant or variable) that participates in an operation.
Plan
2 Simple operations
IO operations
Arithmetic operations
Relational operations
Logical operations
I/O
Input/Output Operators
Operator Designation Role Example
← Assignment Allows changing the con- x ← expression
tent of a variable
Read Input Allows retrieving inputs Read(x,y)
from the keyboard
Write Output Allows sending messages Write(expression)
to the standard output
Remarks
Assignment is done in the following order:
1 The expression on the right is evaluated.
2 The resulting value is transferred to the variable on the left if its type is compatible with
the type of the expression; otherwise, an error is triggered.
variable ← expression
| {z } | {z }
2 1
Arithmetic Operators
Used for numerical calculations.
Remarks
Use parentheses to change the default order of precedence.
If at least one Real number appears in an arithmetic expression of integers, the final
result becomes Real. We say that Real numbers are "contagious" compared to integers.
Relational Operators
These are binary operators, all with the same priority, used for
comparing two objects. The result is typically a Boolean value
True or False, producing Boolean expressions.
Operator Meaning Examples
= '5' = '5' yields True
equality test (same value)
̸ = "med" ̸= "ali" yields True
< less than 5 < 1 yields False
> greater than 5 > 1 yields True
<= less than or equal to
>= greater than or equal to 5 <= 10 yields True
Remarks
Relational operators produce a Boolean result.
They have lower priority than arithmetic operators.
Remarks
Logical operators have lower precedence than relational operators.
Plan
3 Simple Types
Boolean Type
Integer Type
Char Type
Float Type
Booleans
Integers
Represents integers (Z). Integers are stored in RAM using two’s complement (C2):
In a memory cell with size k bits, values in the range {−2k−1 . . . 2k−1 − 1} can be stored.
Positive integers are converted to binary and then stored in k bits (typically k = 32 or 64).
For negative integers, the absolute value is converted to binary and then stored in k bits.
Afterward, the k bits are complemented (logical complement) and then incremented by 1. Thus,
the most significant bit (the k th bit) indicates the sign of the stored value.
Characters
Definition
A character is used to represent:
A lowercase or UPPERCASE letter: 'a', 'A', 'M', 'i' ...
A digit: '0', '4'....
A punctuation mark: '.', ';', '\'' ...
A whitespace character: space, tabulation, newline ' ', '\t', '\n' ...
A control character: no visual or spatial representation: '\o00', '\x200E' ...
Exchange Standards
These symbols are associated with codes (integer numbers) to be able to encode them on a computer
(digitize). The assignment of codes is done according to international standards, the most well-known
ones are:
ASCII : "American Standard Code for Information Interchange " :
A character is encoded on one byte (8 bits).
The standard version only supports the Latin alphabet!
Supported natively by older generation languages: PASCAL, C ...
UNICODE :
Extension of ASCII (Latin letters have the same code).
The code for a character can go up to 4 bytes.
Supports all writing systems. ⇒ allows the exchange of text in any
language, on a global level!
Supported natively by newer generation languages: PYTHON, C#, Java ..
Real Numbers
Values of type Real (floating-point numbers) are stored in a static number of
bytes (usually 8) following the ieee754 standard, which allows representing
decimal numbers of different orders of magnitude but with limited precision
(relative to the size of the number).
The internal representation of floating-point numbers is as follows:
e−1023
f = (−1)s (1.m)2 2
Questions
Questions
1 Write an algorithm to input two real numbers and swap
them using an intermediate variable.
2 Modify the algorithm to perform the swap without using
a third variable.
3 In your opinion, which solution is better? Justify your
answer.
4 Write an algorithm to input a 3-digit integer and
calculate and display the sum of its digits.
Plan
4 Flow-control structures
Fundamental concepts
Conditional Structure
Loops
Fundamental Concepts
Concept of a Block
A block is a group of instructions forming a single behavioral unit. A block consists of
at least one instruction and can contain other sub-blocks ⇒ nested blocks.
Scope of an Object
The scope of an object is the set of blocks where that object is visible. ⇒ The
concept of a block provides a lexical means to define the scope of an object.
Syntax
b0 # pre-processing
if c1 then Execution Flow
b1
else
if c2 then
b2
else
if c3 then
b3
.
.
.
else
if ck then
bk
else
bdefault
end
end
end
end
b0 continuation # post-processing
Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 27 / 57
Chapter 0 : Algorithmic concepts
Flow-control structures
Conditional Structure
Remarks
The conditional structure must always include the if clause.
It’s possible to nest an arbitrary number of control structures (as needed), even zero.
Conditions are evaluated in the order in which they are specified.
The else part is always placed last, and it’s optional.
Example
if (x >= y ) and (x >= z) then
Calculate the maximum of 3 integers: r ←x
else
if y >= z then
Algorithm maximum r ←y
var x, y , z, r : integer else
Begin r ←z
end
Write("Enter 3 integer values: ")
end
Read(x, y , z)
Write("Maximum = ", r )
End
Questions
1 Write an algorithm to solve a first-degree equation in R. Handle all possibilities based on
the 2 coefficients, a and b (real numbers) read from the keyboard.
3 Modify the previous algorithm to offer the user the option to search for solutions in C in
case ∆ < 0. If the user confirms, calculate and display the complex solutions; otherwise,
keep the same behavior as in the previous exercise.
4 Write an algorithm to enter the coefficients of two lines, D1 and D2 , in the plane, and
then display their relative position: coincident, parallel, intersecting, or perpendicular (in
the last two cases, calculate and display the intersection point).
Iterative Structures
Remarks
The while and repeat-until loops are called unbounded loops because they may loop
indefinitely if the continuation or termination condition remains unchanged.
The for loop is called a bounded loop because the number of iterations is known in
advance.
Execution Flow
Syntax b0 prétraitements
b0 # preprocessing F
while ccontinuation do V
CC
bto repeat
end
b0 continuation # post-processing b à répéter
b0_continuation
post traitements
Remarks
The while loop is most suitable when the number of iterations is not known in advance.
The while loop may never run if the continuation condition is initially false ⇒ minimum
number of repetitions = 0.
Ensure that the loop’s condition changes state after a finite number of repetitions.
Example
Euclid’s algorithm is used to find the Algorithm Euclid
greatest common divisor (GCD) of two var a, b, c, x, y : integer
integers a and b. Its principle is illustrated Begin
as follows: Write("Enter two integers: ")
Construct ( two sequences Read(a, b)
a0 = a x ←a
(an )n∈N and y ←b
an = bn−1 for n > 0
( while b ̸= 0 do
b0 = b c ←a
(bn )n∈N
bn = an−1 mod bn−1 for n > 0 a←b
The algorithm involves evaluating the b ← c mod b
terms of these two (decreasing) sequences end
(a0 , b0 ), . . . (ai , bi ), . . . until the first order Write("GCD(", x, ",", y , ")=", a)
k where bk = 0. In this case, ak is the End
GCD of integers a and b.
The repeat loop allows you to create a loop controlled by a condition. The execution flow enters the
loop and continues until the stop condition becomes true.
Execution Flow
b0 pré-traitements
Syntax
b0 # preprocessing
repeat B à répéter
bto repeat
until cstop
b0 continuation # post-processing
V F
b0 post-traitements C
arrêt
Remarks
The repeat loop is most suitable when the number of iterations is not known in advance.
The repeat loop must run at least once because the stop condition is evaluated after the
loop’s body execution. ⇒ minimum number of repetitions = 1.
Ensure that the loop’s condition changes state after a finite number of repetitions.
Example
Algorithm InputValidation
var r : real
Begin
Write("r = ?")
Input Validation: Enter a floating-point repeat
value between 0 and 1. Read(r)
until (r >= 0) and (r <= 1)
End
The for loop allows you to create a loop controlled by a counter. The execution flow enters the loop for
each value taken by the counter in a finite succession of integers.
pré-traitements
Syntax
initialisation
b0 # preprocessing
for ct from start to end step step do
bto repeat V F
end C
b0 continuation # post-processing
B
incrément
post-traitements
Remarks
The for loop is most suitable when the number of repetitions is known in advance.
The for loop may never run when the start value is smaller than the end value (for a
positive step) or vice versa (for a negative step).
The step value must be non-zero, and it cannot be changed during iterations.
Example
Algorithm Factorial
var n, i, f : integer
Begin
Write("n = ?")
Calculate Read(n)
n
Y f ←1
n! = i for i from 1 to n do
i=1 f ←f ∗i
end
Write(n, "! = ", f )
End
Questions
1 Write an algorithm to input an integer n and calculate the sum of its digits.
2 The Fibonacci sequence is defined by the following recurrence relation:
(
F0 = F 1 = 1
(Fn )n∈N =
Fn+2 = Fn+1 + Fn ∀n ∈ N
Write an algorithm to input a natural number n and calculate and display the sum:
n
X
Fi
i=0
3 The Taylor series expansion of the sine function is given by the following formula:
+∞
X (−1)i x 2i+1
sin(x) =
i=0
(2i + 1)!
Plan
Arrays (1/5)
Problem Statement
Imagine an algorithm that operates on the grades of all students at IPEIM.
⇒ One variable per student per subject.
⇒ Thousands of identifiers!!!
Solution
Array ∆=
a vector of homogeneous values (same type) carrying the same identifier and identified by
indices.
Array Dimensions
The number of dimensions of an array is equal to the number of indices required to access an element of
the array.
Arrays (2/5)
Syntax
Declaration of a one-dimensional array:
Algorithm . . .
.
.
.
var T : Array[StartIndex..EndIndex] of ValueType
Arrays (3/5)
Example 2
Fill an array of real numbers with a size
0 ≤ N ≤ 100 read from the keyboard.
Arrays (4/5)
Matrices
Matrices are two-dimensional arrays. Thus, each element of the matrix is referenced by two indices:
The index of its row.
The index of its column.
Declaration of a Matrix
Var M : Array[StartRowIndex..EndRowIndex, StartColumnIndex..EndColumnIndex] of ValueType
Arrays (5/5)
Example 2
Filling a matrix with integers of size 5 × 5
Example 1 Algorithm E2
const N = 5
Var M : Array[1..3, 0..3] of reals type Mat = Array[1..N, 1..N] of integers
The declared matrix will have the following
form: var M : Mat
0 1 2 3
i, j : integer
1 M[1,0] M[1,1] M[1,2] M[1,3]
Begin
2 M[2,0] M[2,1] M[2,2] M[2,3]
for i from 1 to N do
3 M[3,0] M[3,1] M[3,2] M[3,3]
for j from 1 to N do
Read(M[i,j])
Produces a 3 × 4 matrix of real num- end
bers. M[i, j] is a variable of type real
end
∀i ∈ {1 . . . 3} and ∀j ∈ {0 . . . 3}.
...
End
Strings
Definition
Strings are one-dimensional arrays of characters:
var s: string
⇐⇒
var s: array[1..T_MAX] of characters
Syntax
String literals are enclosed in double quotes:
s ← "If the world has absolutely no meaning, why not invent one?"
Questions
1 Write an algorithm to input an integer N and calculate and display the histogram of its
digits. For example, for N = 32432234666998, the program will display H as follows:
0 1 2 3 4 5 6 7 8 9
0 0 3 3 2 0 3 0 1 2
2 Write an algorithm that fills a matrix M with integers. The matrix has l rows and c
columns, where 1 ≤ l ≤ 50 and 1 ≤ c ≤ 20, entered from the keyboard. Then,
calculate three arrays of size c: maximum, average, and variance for each column.
− E (X ))2
Pn
i=1 (Xi
Var(X = (X1 , . . . , Xn )) =
n
3 Write an algorithm to initialize a cube of size 10 × 10 × 10 with values entered from the
keyboard.
4 Write an algorithm to input a string and check if it consists only of alphabetical letters.
Plan
6 Modular Programming
sub-routines
Procedures
Functions
Subprograms (1/3)
Definition
A subprogram is a named block of instructions that is parameterized, meaning it takes inputs and
returns results.
Subprograms (2/3)
Scope of an Object
An object declared in the main program is global, visible everywhere in the code:
In the body of the main program.
In the body of all subprograms defined in the main program.
An object declared in the body of a subprogram is local, visible only within the body of the
subprogram where it is declared.
Subprograms (3/3)
Parameter Passing Modes
There are 3 parameter passing modes, indicating the direction of exchange between the caller and the
callee:
I input parameter:
Must be initialized before calling the subprogram.
Should not be modified inside the subprogram.
It is possible to replace a formal input parameter with an expression of a compatible type
during the call.
O output parameter:
Contains a result.
Must be initialized inside the subprogram.
A formal output parameter is always substituted with a variable of a compatible type
during the call.
IO input/output parameter:
An input object that will be modified by the subprogram.
Always substituted with a variable during the call.
paramètres d’entrée
paramètres d’entrée/sortie
appelant appelé
paramètres de sortie
Procedures (1/2)
A procedure is a named and parameterized block of instructions. Calling a procedure is an instruction (it
does not return a value). Each parameter of the procedure can be passed as E, S, or ES.
Syntax Example 1
A procedure to swap two integer
procedure ProcedureName(M p1 : Type1 , . . ., M variables.
pk : Typek )
procedure Swap(IO x :
const // declaration of local constants
integer, IO y : integer)
type // declaration of local types
var temp : integer
var // declaration of local variables
Begin
Begin
temp ← x
Procedure Body
x ←y
End
y ← temp
End
where M denotes the parameter passing mode.
Procedures (2/2)
Example 2 Example 3
Suppose the following global declarations A procedure to sort an array T containing N
have been made: integers in ascending order using the bubble
sort algorithm.
Functions (1/3)
A function is a named and parameterized block of instructions. The function returns a scalar result
(calling a function is an expression of the same type as the function itself). All function parameters are
passed as E.
Remarks
Syntax The retourner statement
is used to express the
Function FunctionName(I p1 : Type1 , . . ., I pk : result returned by the
Typek ) : Result_Type function. This statement
const // declaration of local constants immediately exits the
type // declaration of local types function and continues
var // declaration of local variables with the calling code.
Begin The parameter passing
Function Body mode for function
return result_expression parameters is not
End mentioned in the
declaration because only
one mode (E) is
supported.
Functions (2/3)
Example 2
Example 1 A function to calculate the index of the max-
imum value in an array T containing N inte-
ger values.
A function to input an integer between two
bounds bmin and bmax (input parameters). Function FindMax(T : Array, N :
integer) : integer
Function InputInRange(bmin : integer, var i, imax : integer
bmax : integer) : integer Begin
var res : integer imax ← 1
Begin for i from 2 to N do
repeat if T [i] > T [imax] then
Read(res) imax ← i
until res ≥ bmin and res ≤ bmax end
return res End
end
return imax
End
Functions (3/3)
Example 4
Example 3 Function to search for a value v in an array
T of N integers.
A procedure using the previous function to
sort an array T in ascending order. Function Search(T : Array, N : integer,
v : integer) : boolean
procedure SortAscending(IO T : Array, var i : integer
I N : integer) Begin
var i : integer for i from 1 to N do
Begin if T [i] = v then
for i from N to 1 step-1 do return True
Swap(T [i], T [FindMax(T , i)])
end
end
End end
return False
End
Questions
1 Write a function to test the primality of an integer.
2 Assuming the following declarations have been made:
const M = 10000
type Tab = Array[1..M] of integers