You are on page 1of 57

Chapter 0 : Algorithmic concepts

Houcemeddine FILALI

Institut Préparatoire aux Etudes d’Ingénieurs de Monastir

Sunday 24th September, 2023


Plan

1 Introduction

2 Simple operations

3 Simple Types

4 Flow-control structures

5 Composite Type (containers/ Iterables)

6 Modular Programming
Chapter 0 : Algorithmic concepts
Introduction

Plan

1 Introduction
Algorithms
Data
Processing

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 3 / 57


Chapter 0 : Algorithmic concepts
Introduction

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]

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 4 / 57


Chapter 0 : Algorithmic concepts
Introduction
Algorithms

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 5 / 57


Chapter 0 : Algorithmic concepts
Introduction
Algorithms

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 7 / 57


Chapter 0 : Algorithmic concepts
Introduction
Data

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.

Const Nmax = 100


Pi = 3.14

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)

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 8 / 57


Chapter 0 : Algorithmic concepts
Introduction
Data

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 10 / 57


Chapter 0 : Algorithmic concepts
Introduction
Processing

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 )

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 11 / 57


Chapter 0 : Algorithmic concepts
Introduction
Processing

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.

Instruction vs. Expression


An instruction changes the state of the program.
An expression produces a value that depends on the program’s state.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 12 / 57


Chapter 0 : Algorithmic concepts
Simple operations

Plan

2 Simple operations
IO operations
Arithmetic operations
Relational operations
Logical operations

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 13 / 57


Chapter 0 : Algorithmic concepts
Simple operations
IO 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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 14 / 57


Chapter 0 : Algorithmic concepts
Simple operations
Arithmetic operations

Arithmetic Operators
Used for numerical calculations.

Priority Operator Arity Meaning Examples


1 () 1 parentheses 2/1+2 gives 4.0, whereas
2/(1+2) gives approxi-
mately 23
+ --5 gives 5
2 1 sign
-
* multiplication 2*4 gives 8
2.0 * 4 gives 8.0
3 2
/ division 3/2 gives 1.5
4/2 gives 2.0
div integer division 10 div 3 gives 3
mod modulus (remainder of integer division) 7 mod 3 gives 1
+ addition 3+ 4.5 gives 7.5
4 2
- subtraction 3-10 gives -7

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 15 / 57


Chapter 0 : Algorithmic concepts
Simple operations
Relational operations

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 16 / 57


Chapter 0 : Algorithmic concepts
Simple operations
Logical operations

Logical Operators (1/2)


These operators allow you to connect relational expressions.

Precedence Operator Arity Meaning Truth Table


1 not 1 logical complement
x not x
False True
True False
2 and 2 logical AND
x y x and y
False False False
False True False
True False False
True True True
3 or 2 logical OR
x y x or y
False False False
False True True
True False True
True True True

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 17 / 57


Chapter 0 : Algorithmic concepts
Simple operations
Logical operations

Logical Operators (2/2)

Remarks
Logical operators have lower precedence than relational operators.

Programming languages use short-circuit evaluation to calculate the result of a series of


conditions connected by logical operators of the form:
cond1 op cond2 op cond3 . . . op condn
If op = and, then condi+1 is evaluated only if condi is True; otherwise, the overall
result is False.
If op = or, then condi+1 is evaluated only if condi is False; otherwise, the overall
result is True.
For example, the condition "x is non-zero and the inverse of x is less than 1" should be
expressed as:
x ̸= 0 and 1/x < 10
to calculate the inverse only when you are certain that x is invertible.
The expression 1/x < 10 and x ̸= 0 leads to a division by zero error when x is zero.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 18 / 57


Chapter 0 : Algorithmic concepts
Simple Types

Plan

3 Simple Types
Boolean Type
Integer Type
Char Type
Float Type

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 19 / 57


Chapter 0 : Algorithmic concepts
Simple Types
Boolean Type

Booleans

This type contains two literal constants representing the two


truth values {True, False}.
Conditional structures, unbounded loops (repeat, while) use a
Boolean expression to trigger/ignore the associated block of
instructions.
Only logical operators are applicable to Booleans.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 20 / 57


Chapter 0 : Algorithmic concepts
Simple Types
Integer Type

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.

Decimal → Binary Conversion Binary → Decimal Conversion

Inputs: n10 = (ak−1 ak−2 . . . a0 )10


where ai ∈ {0 . . . 9}∀i
Output: n2 = (bn−1 bn−2 . . . b0 )2 Inputs: n2 = (bn−1 bn−2 . . . b0 )2
where bi ∈ {0, 1}∀i where bi ∈ {0, 1}∀i
i ←0 Output: n10 = (ak−1 ak−2 . . . a0 )10
n ← n10 where ai ∈ {0 . . . 9}∀i
while n ̸= 0 do n−1
i
X
bi ← n mod 2 n10 ← bi × 2
n ← n div 2 i=0
i ←i +1
end

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 21 / 57


Chapter 0 : Algorithmic concepts
Simple Types
Char Type

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 ..

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 22 / 57


Chapter 0 : Algorithmic concepts
Simple Types
Float Type

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:

←1 bit→ ←− 11 bits −→ ←− 52 bits −→


s=sign e=exponent m=mantissa
⇒ The value of the represented number is

e−1023
f = (−1)s (1.m)2 2

Format of a Floating-Point Literal:


sign integer part . decimal part e exponent

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 23 / 57


Chapter 0 : Algorithmic concepts
Exercise

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 24 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures

Plan

4 Flow-control structures
Fundamental concepts
Conditional Structure
Loops

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 25 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Fundamental concepts

Fundamental Concepts

The 3 Pillars of Programming

Sequence: Do this, then do that.


Selection: Do this if that is true.
Repetition: Do this several times, do this until that...

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 26 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Conditional Structure

Conditional Structures (1/4)


Allows you to choose a block to execute conditionally. The execution flow is directed to the first block
whose associated condition is true.

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

Conditional Structures (2/4)

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 28 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Conditional Structure

Conditional Structures (3/4)

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 29 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Conditional Structure

Conditional Structures (4/4)

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.

2 Write an algorithm to solve a second-degree equation in R. Handle all possibilities based


on the 3 coefficients, a, b, and c (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).

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 30 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Loops

Iterative Structures

In algorithmics, there are three forms of iterative structures:


While Loop : A loop controlled by a condition, the loop’s body is repeated as long as the
continuation condition is true.
Repeat-Until Loop : A loop controlled by a condition, the loop’s body is repeated until the
termination condition becomes true.
For Loop : A loop controlled by a counter (of integer type), the loop’s body is repeated for
each value taken by the counter.

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 31 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Loops

The While Loop (1/2)


The while loop allows you to create a loop controlled by a condition. The execution flow enters the loop
as long as its entry condition is true.

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 32 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Loops

The While Loop (2/2)

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 33 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Loops

The repeat Loop (1/2)

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 34 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Loops

The repeat Loop (2/2)

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 35 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Loops

The for Loop (1/3)

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.

Execution Flow (step > 0)

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 36 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Loops

The for Loop (2/3)

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 37 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Loops

The for Loop (3/3)

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 38 / 57


Chapter 0 : Algorithmic concepts
Flow-control structures
Loops

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)!

Write an algorithm to input a floating-point number x and calculate an approximate


value of sin x by calculating the sum of terms until the absolute difference between two
consecutive terms is less than ε, where 10−4 ≥ ε ≥ 0 (provided by the user).

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 39 / 57


Chapter 0 : Algorithmic concepts
Composite Type (containers/ Iterables)

Plan

5 Composite Type (containers/ Iterables)


Arrays
Strings

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 40 / 57


Chapter 0 : Algorithmic concepts
Composite Type (containers/ Iterables)
Arrays

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 41 / 57


Chapter 0 : Algorithmic concepts
Composite Type (containers/ Iterables)
Arrays

Arrays (2/5)

Syntax
Declaration of a one-dimensional array:

Algorithm . . .
.
.
.
var T : Array[StartIndex..EndIndex] of ValueType

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 42 / 57


Chapter 0 : Algorithmic concepts
Composite Type (containers/ Iterables)
Arrays

Arrays (3/5)

Example 2
Fill an array of real numbers with a size
0 ≤ N ≤ 100 read from the keyboard.

Example 1 Algorithm Example2


const M = 100
Var T : Array[0..3] of integers type Vect = Array[1..M] of reals
The declared array will have the following var T : Vect
form: N, i : integer
Begin
Write(" N= ? ")
repeat
Indices 0 1 2 3
Read(N)
Values T [0] T [1] T [2] T [3]
until (N > 0) and (N <= 100)
for i from 1 to N do
T[i] for ∀i ∈ {0 . . . 3} is a variable of type Write("T[", i, , "]= ?")
integer. Read(T[i])
end
...
End

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 43 / 57


Chapter 0 : Algorithmic concepts
Composite Type (containers/ Iterables)
Arrays

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 44 / 57


Chapter 0 : Algorithmic concepts
Composite Type (containers/ Iterables)
Arrays

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 45 / 57


Chapter 0 : Algorithmic concepts
Composite Type (containers/ Iterables)
Strings

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?"

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 46 / 57


Chapter 0 : Algorithmic concepts
Composite Types

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 47 / 57


Chapter 0 : Algorithmic concepts
Modular Programming

Plan

6 Modular Programming
sub-routines
Procedures
Functions

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 48 / 57


Chapter 0 : Algorithmic concepts
Modular Programming
sub-routines

Subprograms (1/3)

Definition
A subprogram is a named block of instructions that is parameterized, meaning it takes inputs and
returns results.

Advantages of Modular Programming


Subprograms are defined once but can be called multiple times with different parameter values, resulting
in:
Reduced program size.
Improved application structure.
Enhanced code readability.
Better program maintainability.
Code sharing and reusability.
Faster development.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 49 / 57


Chapter 0 : Algorithmic concepts
Modular Programming
sub-routines

Subprograms (2/3)

Formal and Actual Parameters


Parameters used in the subprogram’s definition are formal parameters. Their identifiers represent
fictional objects describing what needs to be done when the subprogram is invoked.
Parameters used when calling a subprogram are actual parameters. Their identifiers represent
real objects manipulated by the instructions within the subprogram.

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 50 / 57


Chapter 0 : Algorithmic concepts
Modular Programming
sub-routines

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 51 / 57


Chapter 0 : Algorithmic concepts
Modular Programming
Procedures

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 52 / 57


Chapter 0 : Algorithmic concepts
Modular Programming
Procedures

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.

procedure BubbleSort(IO T : Arr, I N :


const M = 100 integer)
type Arr = Array[1..M] of var i, j : integer
integers swapped : boolean
Begin
j ←N−1
A procedure to fill an array T with N inte- repeat
gers read from the keyboard (N is an input swapped ← True
parameter) for i from 1 To j do
if T[i] > T[i+1] then
procedure Fill(O T : Arr, I N : integer) Swap(T[i], T[i+1])
var i : integer swapped ← False
Begin end
for i from 1 To N do end
Read(T[i]) j ←j −1
end until swapped
End End

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 53 / 57


Chapter 0 : Algorithmic concepts
Modular Programming
Functions

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.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 54 / 57


Chapter 0 : Algorithmic concepts
Modular Programming
Functions

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 55 / 57


Chapter 0 : Algorithmic concepts
Modular Programming
Functions

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

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 56 / 57


Chapter 0 : Algorithmic concepts
Modular Programming

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

Write a procedure that takes an integer N ≤ M as input and


produces an output of an array of type Tab, with its elements
filled by the first N prime numbers.
3 Write a function that takes as input an array T of type Tab
(assumed to be sorted in ascending order), an integer N
indicating the number of filled cells in T , and another integer
c. The function should return a boolean indicating whether
the array contains the value c or not.

Houcemeddine FILALI Chapter 0 : Algorithmic concepts IPEIMonastir 57 / 57

You might also like