0% found this document useful (0 votes)
7 views46 pages

Advanced Data Structure I-3

This document provides an overview of algorithms, defining them as methods for solving problems in a finite time and differentiating between algorithms and programs. It outlines the steps for problem-solving, the structure of algorithms, variable types, and basic instructions in pseudocode. Additionally, it discusses programming languages and the importance of variable declaration and assignment in algorithm development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views46 pages

Advanced Data Structure I-3

This document provides an overview of algorithms, defining them as methods for solving problems in a finite time and differentiating between algorithms and programs. It outlines the steps for problem-solving, the structure of algorithms, variable types, and basic instructions in pseudocode. Additionally, it discusses programming languages and the importance of variable declaration and assignment in algorithm development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Basics Concepts of algorithm

In this chapter, we present basic notions about algorithms, i.e. how to write an algorithm that
solves any given problem.

I. Algorithm concept
1. Definition
A computer program allows the computer to solve a problem, but before communicating to the
computer how to solve this problem, we must first be able to solve it ourselves: that is to create
an algorithm.

Algorithmics refers to the discipline that studies algorithms and their applications in computer
science .

An algorithm is a method for solving a given problem in a finite time.

Problème

Algorithme Résultat

Données

The program will only be the translation of the algorithm into a programming language, that is
to say, a language simpler than French in its syntax, without ambiguities, which the machine can
use and transform to execute the actions. that he can describe. Pascal, C, Java and Visual Basic
are names of programming languages.

2. Algorithm and program


We have defined the notions of program and algorithm. However, it is noted not to confuse these
two notions because there are differences between the two. Among the differences we can have:

 The development of an algorithm precedes the programming stage


 A program is an algorithm
 A programming language is a language understood by the computer

1
 Developing an algorithm is a demanding problem-solving process
 Writing an algorithm is a thought exercise that is done on paper
 The algorithm is independent of the programming language, for
example, we will use the same algorithm for an implementation in Java,
or in C++ or in Visual Basic
 The algorithm is the raw solution of a computer problem.

3. Representation of an algorithm
Historically, there are two ways to represent an algorithm:
 The Organization Chart : graphic representation with symbols
(squares, diamonds, etc.)
 Provides an overview of the algorithm
 Representation almost abandoned today
 Pseudo-code : textual representation with a series of conventions
resembling a programming language (this is an informal language close
to natural language and independent of any programming language).
 It is more convenient to write an algorithm
 Its representation is widely used

II. Steps for resolving a problem


1. Steps
To solve a problem and transcribe it into an algorithm, it is useful to follow a rigorous approach.
To do this we can follow the following steps:

1) Understanding the problem statement


2) Break the problem down into sub-problems that are easier to solve
3) Associate a specification with each sub-problem:
 The necessary data
 The resulting data
4) The procedure to follow to arrive at the result starting from a set of
data.
5) Development of an algorithm.

2
Once the algorithm has been established, it is now necessary to create the corresponding
program.

2. Creating a program
Solving a given problem involves a succession of steps, namely:

Problem → Explicit statement → Algorithm → Program

When writing a program, you may encounter 2 types of errors:

 Syntactic errors : they are noticed during compilation and are the result of poor writing
in the programming language.
 Semantic errors: they are noticed at execution and are the result of poor analysis. These
errors are much more serious because they can be triggered while the program is running.

To write a program you must choose a programming language that corresponds to it:

3. Programming languages (computer languages)


A programming language is a communication code, allowing a human being to communicate
with a machine by submitting instructions to it and analyzing the hardware data provided by the
system. The programming language is the intermediary between the programmer and the
machine. It allows you to write programs (consecutive series of instructions) intended to carry out
a given task.

There are two types of languages:

 Procedural languages : Fortran, Cobol, Pascal, C, etc.


 Object-oriented languages : C++, Java, C#, etc.

Choosing a programming language is not easy, each one has its specificities and corresponds
better to certain types of uses.

3
Variables, Types and Basic Instructions
I. THE VARIABLES
1. Basic Structure
In pseudo-code the general structure of an algorithm is as follows:

Algorithm algorithm_name

CONST {Definition of constants}

TYPE {Type Definition}

VAR {Variable declaration}

BEGIN

{Continuation of statements}

END .

 Header part: this is the first line of the algorithm, it begins with the word algorithm
followed by a space then the name of the algorithm.
 Declarations part: in this part, all objects used in solving the problem must be declared.
 Processing part: this part begins with the word Start and ends with the word End. It
contains the actions used in resolving the problem.

2. Concept of variable
The data manipulated in an algorithm are called variables . A variable is used to store the value
of data in a programming language. It designates a memory location whose contents can change
during a program (hence the name variable).
Each memory location has a number that allows you to refer to it uniquely: this is the memory
address of this cell.

a. Ruler
The variable must be declared before being used, it must be characterized by:

 A name (Identifier)

4
 A type which indicates all the values that the variable can take (integer, real, boolean,
character, character string, etc.)
 A value

b. Identifiers: rules
The choice of the name of a variable is subject to a few rules which vary depending on the
language, but in general:

 A name must begin with an alphabetical letter. Example: E1 (1E is not valid)
 Must consist only of letters, numbers and the underscore (“_”) (Avoid punctuation
characters and spaces). Examples: SMI2008, SMI_2008. (SMP 2008, SMP-2008,
SMP;2008: are invalid)
 Must be different from the reserved words of the language (for example in C: int, float,
double, switch, case, for, main, return, …)
 The length of the name must be less than the maximum size specified by the language
used (in c, the name must be at most 32 characters).
 In c, upper case letters are distinguished from lower case letters: a and A are two different
nouns.

Tip: for code readability, choose meaningful names that describe the data being manipulated.
Examples: NoteStudent, Price_includes tax, Price_excl. tax.

Note: in algorithmic pseudo-code, we will respect the rules cited, even if we are free in the
syntax.

II. Types of variables


The type of a variable determines the set of values it can take, but also tells the machine the size
of the memory space necessary to store the variable.

In algorithmic language there are 4 basic types of variables. We can cite: integers , real
numbers , characters and booleans .

1. The integers
They represent integers, the operations that can be used on integers are:

5
 All basic elementary operations are permitted: + (addition), - (subtraction), * (product), /
(division)
 The classic comparison operators: <, >, =, ...
 The division / is the Euclidean (or integer) division. Ex: 11 / 4 = 2 and not 2.75!)
 There is the modulo % operator, which gives the remainder of the Euclidean division. Ex:
11%4 = 3

2. The real
To represent integers, the operations that can be used on integers are:

 Classic arithmetic operations: + (addition), - (subtraction), * (product), / (division)


 The classic comparison operators: <, >, =, ...
 Division / gives a decimal result
 The modulo % operator does not exist

3. The characters
This is the domain made up of alphabetic and numerical characters. A variable of this type can
only contain one and only one character. The elementary operations that can be performed are
comparisons: <, >, =, ...

NB: there are other Operations on characters:

 SUCC(c): next character in the ASCII table;


 PRED(c): previous character in the ASCII table.

4. Booleans
A logical type variable (boolean) can take two values: TRUE (1) or FALSE (0).
The most used main operations are:

 Logical operators: NOT, AND (&&), OR(||)

Truth tables :

A B A AND B A OR B A NOT A
FAKE FAKE FAKE FAKE FAKE TRUE
FAKE TRUE FAKE TRUE TRUE FAKE
TRUE FAKE FAKE TRUE

6
TRUE VAI TRUE TRUE

 Comparison operators: =, ≤, ≥, ≠

5. Variable declaration
Any variable used in a program must have been the subject of a prior declaration. In pseudo-
code, the declaration of variables is carried out in the following form:

Identifier list variables: type

Example :

Variables i, j, k: integer

x, y: real

OK: boolean

c1, c2: character

Declaring a variable amounts to reserving a memory location for it. We don't know its initial
value!

6. Concept of constant
A constant is a variable whose value does not change during the execution of the program; it can
be a number, a character, or a string of characters. In pseudo-code,

Constant identifier=value (by convention, constant names are in capital letters)


Example: to calculate the area of circles, the value of pi is a constant but the radius is a variable.

 Constant PI=3.14, MAXI=32


 A constant must always be assigned a value as soon as it is declared.

7
III. Basic Instructions
In what follows we describe the list of basic operations that can make up an algorithm. They are
described in pseudocode (pseudolanguage).

An algorithm is made up of four types of instructions considered as small basic building blocks:

1) Assigning variables
2) Reading and/or writing
3) The tests
4) Buckles

1. Assignment
Assignment consists of assigning a value to a variable (i.e. filling or modifying the contents of a
memory area). In pseudo-code, the assignment is denoted by the sign ← .

 test← e : assigns the value of e to the test variable


 e can be a value, another variable or an expression
 test and e must be of the same type or compatible types

The assignment only modifies what is to the left of the arrow

Examples 1 : i ←1, j ←i, k ←i+j, x ←10.3, OK ←FALSE, c1 ←'I', c2 ←c1, x ←4, x ←j (with i,
j, k: integer; x: real; ok: boolean; c1, c2: character)

Invalid examples: i ←10.3, OK ←"I", j ←x

Examples 2

a ←10 a receives the constant 10

a ← (a*b)+ca receives the result of (a*b)+c

d ←'m' d receives the letter m

Remarks :

 The C programming language uses the equal sign = for the ← assignment.
 During an assignment, the expression on the right is evaluated and the value found is
assigned to the variable on the left. So, A←B is different from B←A

8
 Assignment is different from a mathematical equation:
 The operations x ← x+1 and x ← x-1 have meaning in programming and are called
increment and decrement respectively.
 A+1 ← 3 is not possible in programming languages and is not equivalent to A ← 2
 Some languages give default values to declared variables. To avoid any problems it is
preferable to initialize the declared variables.

2. Reading
Read(variable)

This operation makes it possible to assign to a variable a value entered by means of an input
device (generally the keyboard).

Reading Examples

Read(a) The user is asked to enter a value for a


Read(a,b,c) The user is asked to enter 3 values for a, b and c respectively

Note: The program stops when it encounters a Read instruction and continues only after the
expected input is entered using the keyboard and the Enter key (this key signals the end of the
input).

Advice: Before reading a variable, it is strongly recommended to write messages on the screen,
in order to warn the user of what to type.

3. Writing
Write(expression)

It communicates a given value or a result of an expression to the output organ.

Writing examples
Write('hello') Displays the message hello (constant)

Write(12) Displays the value 12

Write(a,b,c) Displays the values of a, b and c


Write(a+b) Displays the value of a+b

9
Write(a, b+2, "Message") Displays the value of a, then the value of the expression b+2 and
finally the word ''message''.

4. General syntax of the algorithm


Algorithm Example
Const var1=20 , var2="hello!"
Var var3, var4: realvar5: character
begin // body of the algorithm
Instructions 1Instructions 2………….
Instructions
END
Notes:
 The instructions of an algorithm are usually executed one after the other, in sequence (top
to bottom and left to right).
 The order of execution is important
 We cannot change this sequence arbitrarily

5. Expressions and operators


An expression can be a value, a variable or an operation made up of variables linked by
operators.

Examples: 1, b, a*2, a+ 3*bc, …

Evaluating the expression provides a single value that is the result of the operation.

The operators depend on the type of operation, they can be:

 Arithmetic operators: +, -, *, /, % (modulo), ^(power)


 Logical operators: NOT(!), OR(| |), AND (&&)
 Relational operators: =, <, >, <=, >=
 Operators on strings: & (concatenation)
 An expression is evaluated from left to right but taking into account the priorities of the
operators.

Noticed :

10
 You cannot add an integer and a character
 However, in certain languages we can use an operator with two operands of different
types, this is for example the case with arithmetic types (4 + 5.5)
 The meaning of an operator can change depending on the type of operands, e.g.
 The + operator with integers performs the addition, 3+6 is 9
 With character strings it performs concatenation, “hello” + “everyone” equals “hello
everyone”

6. Operator priority
For the arithmetic operators given above, the order of priority is as follows (from highest priority
to lowest priority):

 (): parentheses
 ^: (elevation to power)
 *, / (multiplication, division)
 % (modulo)
 +, - (addition, subtraction)

Example: 9 + 3 * 4 is 21

 If necessary, parentheses are used to indicate the operations to be carried out as a priority.
Example: (9 + 3) * 4 is 48
 With equal priority, the expression is evaluated from left to right

7. Boolean operators
 Associativity of operators and and or . Example: a and (b and c) = (a and b) and c
 Commutativity of operators and and or Example: a and b = b and a ; a or b = b or a
 Distributivity of operators and and or Example: a or (b and c) = (a or b) and (a or c) ; a
and (b or c) = (a and b) or (a and c )
 Involution ( homography reciprocal ): no no a = a ; Morgan's Law: not (a or b) = not a
and not b ; no (a and b) = no a or no b
Example: let a, b, c and d be any four integers:
(a<b)| |((a>=b)&&(c==d))↔ (a<b)| |(c==d) because (a<b)| |(!(a<b)) is always true

11
Conditional Statement
This chapter deals with the notions of conditions (simple, Boolean, compound conditions) then
introduces conditional structures ( If, If-Then and If-Else-If ) and defines the choice tree. The
Complements describes the selective According as well as the If- expression operator.

I. Conditions
1. Comparison operators
Also called relational operators or comparators, they generally act on numeric variables or strings
and give a Boolean result. For characters and strings, the alphabetical order determines the result.

Table 1: Mathematical operators

Mathematical Algorithmic
Meaning
operators equivalent
< Strictly less than <
≤ Less or equal <=
> Strictly superior >
≥ Greater than or equal to >=
= Equality =
≠ Different or inequality <>

2. Simple condition
Denoted v1 Φ v2 , it associates a comparison operator Φ and two values v1 and v2 of the same
nature (same type or comparable types) and delivers a Boolean result:

 True: we say that the condition is verified


 False: case of unverified condition

Examples

 eval(2<3) is True .
 eval(6*3=13) is False .
12
 eval('A'<'E') is True because the alphabetical order is respected in the ASCII codes
assigned to the letters.
 eval("milou"<"tintin") is True as is eval("assembler"<="java") .
 eval('a'<'A') is False because uppercase letters come before lowercase letters.
 eval("Hello">"Good day") is False because the space is before the letters.
 If n1 and n2 are two integer variables containing the values 7 and 5, eval(2*n1>n2+3) is
eval(2*7>5+3) i.e. eval(14>8) therefore True .

NB: Unlike mathematics, comparison operators cannot be chained . Thus, to check if a


number x ∈ [a..b], we must write: (a <= x And x <= b)

3. Compound condition
More simply condition or logical expression Noted b1 Ψ1 b2 Ψ2. . ., it associates logical
operators Ψi and Boolean values bj and delivers a Boolean result ( True or False ). It allows
simple conditions to be linked into a single “super-condition”.

Examples:

 The integer a must be strictly greater than zero and strictly less than 100: a > 0 And a <
100
 Color c must be Red, Green or Blue: c = Red Or c = Green Or c = Blue
 Color c must not be Black: No (c = Black)
 “At a crossing light, I stop if it is red or orange and if my speed is less than 40km/h. In
other cases, I pass. »: stop <- (light = red) Or (light = orange And speed < 40) pass <-
No stop

Lazy evaluation of And and Or operators


a. Principle of lazy evaluation
Also known as shortcut evaluation, it is carried out from left to right and only the conditions
strictly necessary for determining the logical value of the expression are evaluated.

13
Lazy evaluation saves time but above all it avoids execution errors .

Example :

Consider the expression:


n <> 0 And m / n > 10
If n is zero, the lazy evaluation gives the result False immediately after testing the first condition
without evaluating the second, while a complete evaluation would cause the algorithm to stop due
to division by 0.

b. Non-commutativity of And and Or


Lazy evaluation results in:

c1 And c2 is not equivalent to c2 And c1

4. Examples: Priority and evaluation

a. Example: Operator precedence


Consider the logical expression:

not a+2<30 or (bc/2=28 and c^11>2000*c+1)

It is equivalent to:

(no((a+2)<30))

or (((b-(c/2))=28) and ((c^11)>((2000*c)+1)))

The formula with sub-braces is:

14
b. Example: Lazy evaluation
The table below collects the evaluations of the Boolean expression:

expr <-- (A > 10 and A <= 12) or (not (B > 10))

For example, the second column of the table shows that if A contains 0 and B contains -3, then
Boolean evaluation of expr returns True . Additionally, if the box is empty, this means that the
condition is not evaluated due to lazy evaluation.

Table 2: Running a lazy evaluation

HAS 0 11 13
B -3 16 16
A > 10 FAKE TRUE TRUE
A <= 12 TRUE FAKE
A > 10 and A <= 12 FAKE TRUE FAKE
B > 10 FAKE TRUE
no (B > 10) TRUE FAKE
expr <- (A > 10 and A <= 12) or (not (B > 10)) TRUE TRUE FAKE

II. Selective If, If-Then and If-Else-S


1. Selective If
It translates: If the condition is true , execute the instructions Then , Otherwise execute the
instructions Otherwise . This is a binary choice: one and only one of the two sequences is
executed.

The condition can be simple or complex (with parentheses and/or logical operators And, Or,
Not).

15
2. Selective If
If condition SO
| instructionsSo
Otherwise
| instructionsOtherwise
End if
The body of the “ then” clause starts after the word So and ends with the
word Otherwise . That of the “ otherwise” clause starts after the word
Otherwise and ends with the word FinSi .

Example: Selective If and If-Then

This example enters a student's yearly average in an integer avg and then
displays one of two messages:

You are not moving up to the next year Bravo, you are moving up to the next
year

The first is displayed if avg < 10 , otherwise it is the second. And in the case
where 16 <= avg <= 20 , it also displays:

With the congratulations of the jury

Algorithm pgpassage1
variable avg : real
Begin
Write("Enter average")
read(avg)
If (avg < 10) Then
write("You are not moving on to the next year")
else
write("You are moving to the next year")
If (16 <= avg And avg <= 20) Then
write("With the congratulations of the jury")
End if
End if
END
The first condition is a simple condition: avg < 10 , and the second condition
a compound condition: 16 <= avg And avg <= 20 .

16
3. Selective If-Else-If
It successively evaluates the conditionI and executes the instructionsI if it is
verified. If all n conditions fail, executes the Else instructions .

If condition1 SO
| instructions1
Else If condition 2 Then
| instructions2
Else if...
| ...
Else If conditionN SO
| instructionsN
else
| instructionsOtherwise
End if
Question How does the algorithmic language distinguish between an If - Else - If structure and
cascading If structures ?
Answer When the keywords Otherwise and If are found in succession on the same line, the
language activates the interpretation of an If - Else - If structure .

III. Supplements
1. Selective According
According structure is a simplification of writing several nested alternatives.
Two forms exist:

 Selective According (lists of values)


 Selective According to (conditions)

The form accepted by most programming languages is that with lists of


values.

 Selective According (lists of values)

If expr = one of the values in list1 Then


# instructions when the value is in list1
Else If expr = one of the values in list2 Then
# instructions when the value is in list2
Otherwise If ...

17
Else If expr = one of the values in listN Then
# instructions when the value is in listN
Otherwise
# instructions when the value of the variable # is not found in any of the
previous lists
End if
 Selective According to (conditions)
If condition1 Then
# instructions when condition1 is true Else If condition2 Then
# instructions when condition2 is true
Otherwise If ...
Else If conditionN Then
# instructions when conditionN is true
Otherwise
# instructions to execute when none of the # preceding conditions are true
End if

2. Selective According (lists of values)


It evaluates the expression and executes only I instructions that match the
ordinal value Ci (i.e. integer or character type). The Other Case clause is
optional and allows you to handle all cases not previously handled. This is the
classic multi-conditional instruction of languages

According to expression
| Case list1 of values separated by commas
| | instructions1
| | ...
| Case listN of values separated by commas

18
| | instructionsN
| Case Other
| | instructionsOtherwise
EndAccording to
Note: Care must be taken not to appear the same value in several lists.
According to is less general than If:
 The expression must be a discrete value (Integer or Character).
 Cases must be constants (no variables).
If these rules are verified, the According is more efficient than a series of Cascading Ifs (because
the expression of the According is only evaluated once and not in each of the Ifs).

3. Selective According to (conditions)


This is a simplification of writing nested alternatives.

According to
| condition1
| | instructions1 (when condition1 is true)
| ...
| conditionN
| | instructionsN (when conditionN is true)
| Other
| | instructions Otherwise (none of the conditions checked)
EndAccording to

Make sure that the conditions do not <overlap> , i.e. that no two of them are
ever true simultaneously.

4. Example: Day of the week in plain text


The algorithm enters a day of the week as an integer (0 for Sunday, 1 for
Monday, etc.) and displays in plain text the day of the week for a work day
and <Weekend> for Saturday or Sunday. In all other cases, it displays <
Invalid day number > .

Algorithm PGJsem1
Variable jr: Integer
begin
| write (“Number of the day”)

19
| read (jr)
| According to jr
| | Case 1
| | | write ("Monday")
| | Case 2
| | | write ("Tuesday")
| | Case 3
| | | write (“Wednesday”)
| | Case 4
| | | write ("Thursday")
| | Case 5
| | | write ("Friday")
| | Case 0, 6
| | | write ("Weekend")
| | Case Other
| | | write ("Invalid day number")
| EndAccording to
END

5. If-expression operator
Ifi(exprBool, exprThen, exprElse)

Evaluates the logical expression exprBool and if it is verified, performs the expression exprThen,
otherwise the expression exprElse. The exprThen and exprElse must be of the same type. This
very shortened syntax should be reserved for small tests.

Loop

When you want to repeat an operation or a block of operations several times


in an algorithm, it is possible to use repetitive (iterative) structures called
loops. There are three types of loops: 'While', 'Repeat' and 'For'.

I. The While loop


The format of the while loop is:

While <Condition> Do
Instructions …
EndWhile.
This structure allows the repetition of a sequence of operations as long as the condition is
satisfied (= TRUE). When the condition becomes false the loop is finished. The condition is a

20
logical expression. This expression must then be able to change its value (have the value FALSE)
to exit the loop and avoid the case of the “infinite loop”. The sequence is one or more operations.
For several operations, the start and end are mandatory. In the case of a single operation, the start
and end are optional.

Let's see the following example which allows us to display values from 1 to 10:

Algorithm displaysvalue
Var i: integer
Beginning
Write (“the following program displays values from 1 to 10“)
i←1;
While (i <= 10) Do
Write (i)
i←i+1
end While
END

II. The Repeat loop


General format:
Repeat
Instructions …
Until <Condition>

This structure allows the repetition of one or more operations until a condition is verified (=
TRUE). To avoid the infinite loop, the condition must be able to change its value (have the value
TRUE). The sequence can contain one or more operations. In both cases, start and end are
optional.
Let's take the example to display values from 1 to 10:
Algorithm displaysvalue
Var i: integer
Beginning
Write (“the following program displays values from 1 to 10“)
i←1;
Repeat
Write (i)
i←i+1
up to (i>10)
END

21
Note: For the While and Repeat loop, we often use a variable, called an index, initialized to an
initial value before executing the loop. Inside the loop, the index will be incremented (by adding
a value to the current value), or decremented (by decreasing the current value) to reach the loop
stopping condition. In addition, we execute the repeat loop code at least once before testing the
condition.
The following table summarizes the differences between the two loops While and Repeat:
Table 3: Comparison between while and repeat loops

Loop Condition of Condition to Number of Start and end


execution exit executions for the
sequence
As long as Condition = Condition = is not known in Mandatory if the
TRUE FAKE advance, but it sequence
may never be contains several
executed if the operations, and
condition = optional if the
FALSE from the sequence
start contains a single
operation
Repeat Condition = Condition = is not known in Optional in both
FAKE TRUE advance, but it is cases.
executed at least
once.

III. The For loop


Its general format is:

For Counter from Initial Value to Final Value do

Instructions …

EndFor

This structure makes it possible to repeat a sequence of operations for all the values of a variable
called control variable (Counter) from an initial value to a final value. The number of
repetitions of the sequence of instructions is known in advance . After each execution of the
loop body, the control variable is increased by one unit (Increment). The default value of the
increment is equal to 1 (in case it is not specified). The control variable is of type integer. The

22
initial value and final value are constants or integer variables. These two values make it possible
to calculate the number of repetitions of the sequence:

nbr = final value - initial value + 1 (in the case where the step is equal to 1).

Let's take the example to display values from 1 to 10:


Algorithm displaysvalue
Var i: integer ;
Beginning
Write (“the following program displays values from 1 to 10“)
For I from 1 to 10 do
Write (i)
endFor
END

Notes: In a For loop, the counter (control variable) can be used, but it should never be changed
inside the loop.

IV. Nested loops


Loops can be nested inside each other. A While loop can contain another While loop, another
Repeat loop, or another For loop, and vice versa. Additionally , a loop can contain another loop,
which itself can contain another loop and so on.

The following algorithm displays multiplication tables from 1 to 10.

algorithm Nested_loops
Var i, j: integer
Beginning
i←1
As long as (i<=10) Do
j←1
Repeat
Write (i, '*', j, '=', i*j)
j←j+1
Until (d > 10)
i←i+1
EndWhile
End .
This code can be rewritten as follows:

algorithm Nested_loops
Var i, j: integer
Beginning

23
For i from 1 to 10 Do
For d from 1 to 10 Do
Write (i, '*', j, '=', i*j)
EndFor
EndFor
End .

Chapitre 1. Arrays
The types presented so far are simple types. There are other so-called structured (complex) types.
A structured type is any type defined on the basis of other types. Starting with the type that we
consider the most important of the structured types, namely the array type.

I. The array type


A table is a homogeneous structure composed of a set of elements of the same data type. General
format:

Tab_name: Array [min_index .. max_index] of data_type.

A table has a name (Tab_Name). It is also characterized by two indices (index_min, index_max).
The type of array elements is indicated by data_type.

For example, to declare a Note array of ten real elements we put:

Note: Table [1..10] of real;.

This example allowed us to replace the declaration of 10 variables Note1, Note2, …, Note10 of
real type with a single structure, namely the Note table.

The capacity of an array (the number of elements the array can hold) cannot be changed during
the execution of a program. The size of the table must therefore be large enough for handling. For
programming flexibility, we can use a constant as follows:

const Max = 10;


var Note = Array[1..Max] of real;
Remarks :

24
 The two indices (index_min, index_max) must be of ordinal type (scalar or discrete),
generally integer. A type is said to be ordinal if its elements are countable, ordered with a
min value and a max value.
 The two indices allow you to calculate the number of elements in the array. In the case of
integer type, nbr_elements = max_index - min_index + 1.

1. Manipulating a table
A table can be represented by a set of boxes, one next to the other, or one under the other,
schematized as follows:

Table 4: Representation of the table Note

1 2 3 4 5 6 7 8 9 10

An array element is accessible by its position (index) in the array. The Note array is a single-
dimensional array, where each element is accessible by a single index. For example Note[1] ←
0.25; allows you to assign the value 0.25 to the first box in the table. The Note table becomes:

1 2 3 4 5 6 7 8 9 10
0.25
The index can be expressed directly as a plaintext number. It can also be a variable or a
calculated expression. For example:

algorithm exe_tab
Var T: array [1..5] of integer
X: integer
Begin
X←3
T[1] ← 7
T[X] ← 18
T[X-1] ← 4
END.
After executing the algorithm operations, the table T is represented as
follows:

1 2 3 4 5
7 4 18

25
Remarks: For manipulating arrays, loops are frequently used.

Example: (Creation, initialization and editing of a table)

Problem: Write the algorithm to create an array of ten integers, initialize its elements to 0, then
display them.

Solution :

algorithm init_tab
Var T: array [1..10] of integer
i: integer
Begin
For i from 1 to 10 Do
T[i] ← 0
EndFor
For i from 1 to 10 Do
Write (T[i])
EndFor
END.

2.

II. Two-dimensional array


An array element can itself be of array type. For example, Note: Array [1..10] of Array [1..3] of
real; In this case, an array element is accessible by two indices.
For example, Note[4][2] ← 5; or Note[4,2] ← 5;
A second method is to use a single two-dimensional array for the rows and columns. General
format:
Tab_name: Array [indl_min..indl_max, indc_min..indc_max] of data_type
The following example allows you to declare an array of real numbers named Note in two
dimensions 3 * 10:
Note: Table [1..3, 1..10] of real.
A two-dimensional table can be represented by a set of boxes organized into rows and columns,
and schematized as follows:
1 2 3 4 5 6 7 8 9 10
1 0.25 11 55 29.06 17.5 0.5 0 43 10 10.25

26
2 30.77 166 5.44 9.6 7.57 10.5 770 4.83 510 10.5
3 0.62 61 0 2.06 17.5 80.95 0.04 473 10 1.25
An array element is accessible by two indices (row and column). For example, Note[2,3]=5.44.
The most used tables are one or two dimensions, but it is possible to define tables with three or
four dimensions, or even more. For example :
Note: Array [1..10, 1..3, 'a'..'z', boolean] of real.
Note: We sometimes use the term vector to designate a one-dimensional array and the term
matrix to designate a two-dimensional array.

Chapitre 2. Procedures and functions


When we have to write an algorithm to solve a complex problem, it is in our interest to
decompose the problem into sub-problems. For each of these subproblems we write a subroutine
which will be called by the main algorithm. A subroutine can be a procedure or a function.

A subroutine is specified by a name and optionally a list of formal parameters (declarative


parameters). Formal parameters, if they exist, specify data and/or results of the sub-problem to be
solved.

I. The procedures
The iterative (or repetitive or repetition) action as allows you to repeat the execution of a block of
actions 0 or more times.

1. Statement
A procedure has the following general form:

Procedure Name (lists of formal parameters with their types separated by ',')
Declaration of local variables of the procedure
Beginning
List of actions (instructions) of the procedure
END

27
2. Types and modes of passing parameters

a. Types of formal parameters


There are three types of parameters in a subroutine:

 Data parameters : they do not change value in the subroutine. Rather, their values are
used.
 The results parameters : they only have meaning after the execution of the subroutine.
Rather, their values are used.
 Data/results parameters : they have a value before the execution of the subroutine and
which can change after execution.

b. Methods of passing formal parameters


There are two modes of passing parameters:

 Passing by value: (given parameters) the formal parameter represents a local variable to

the subroutine and any change of parameter has no effect on the effective parameter.

When called, the values of the effective parameters are retrieved in the formal parameters

on which the processing is carried out. In the following statement:

Test procedure (p1: type1, p2: type2, p3: type3, …, pn: typen) the parameters p1, p2, p3, …,

pn are passed by value.

 Passage by address: (data/results parameters or results parameters) the principle consists

of associating with the formal parameters the address of the effective parameters. Any

changes to the settings affect the effective settings.

In the following statement:

Test procedure (p11: type11, p12: type12, …, p1n: type1n, var p21: type21, var p22: type22, …,

var p2n: type2n) the parameters p11, p12, …, p1n are passed by value and the parameters p21,

p22, …, p2n are passed by address.

28
Note: Parameters passed by address are preceded by the var keyword.

c. Calling a procedure
In a main algorithm, a procedure is called in an action by specifying its name and its parameters

which become effective parameters with the respective (or real) passage mode. Thus, if a

procedure is declared with the header:

Test procedure (p11: type11, p12: type12, …, p1n: type1n, var p21: type21, var p22: type22, …,
var p2n: type2n)
Then, at the time of the call with the real or effective parameters q11, q12, …, q1n passed by

value and the parameters q21, q22, …, q2n passed by address, the action takes the form:

test(q11, q12, …, q1n, &q21, &q22, …, &q2n)

Note: Formal parameters and effective parameters can have the same name.

d. Example of calling a procedure


Write a procedure for calculating and displaying the sum of the first n integers.

Procedure Sum(n: integer)


Var i, s: integer
Begin
s←0
for i from 1 to n do
s←s+i
end for
write(“the sum of the “, n, “ first integers is: “, s)
END ;
A primary algorithm that calls this procedure enters a value for n and calls the procedure in an

action by specifying the name of the procedure and a value of n that becomes an effective

parameter.

Algorithm calculationSumN_prime_Integers
Var n: integer
Beginning
Write(“Give a value for n“)
Read(n)
29
Sum(n)
END
II. Functions
A function is a subroutine that renders a unique result of scalar type (integer, real, character,
boolean, string, array, etc.).

1. Statement
A function has the following general form:

Function Name(lists of formal parameters with their types separated by ','): result_type
Declaration of local variables of the function
Begin
List of actions (instructions) of the function
Function_name ←varialble_result_type
END
Note: Formal parameters of the function can only be given parameters.

2. Calling a function
As a function renders a unique result, its call is made in the main algorithm by assigning the
returned result to a variable declared in this algorithm. The call takes the following form:
Identifier ← Function_name(listOfEffectiveParameters)
Note: the types of the identified variable and the result must be compatible.

3. Example of a function
A function for calculating the sum of n prime integers.
function Sum(n: integer): integer
Var i, s: integer
Beginning
s←0
for i from 1 to n do
s←s+i
end for
sum←s
END
A main algorithm that calls this function enters a value for n and calls the function in an action
that assigns the result it returns to a variable declared in the algorithm.
Algorithm calculationSumN_prime_Integers
Var n,s: integer

30
Beginning
Write(“Give a value for n“)
Read(n)
Sum(n)
END

Recordings
This chapter presents the record data type which is used to represent, in the same variable, a finite

number of data of heterogeneous types.

I. Definition
A record is a data structure used to store, in the same variable, a finite number of elements of

heterogeneous types. In memory this variable is associated with a memory space sized to a finite

number of boxes of heterogeneous dimensions that can contain its elements. A record type

variable is called a Composite variable .

II. Statement
A record type variable is declared as follows:

Type type_name = Record


Field 1: typeElm1
Field 2: typeElm2
…………………..
Field n: typeElmn
END
Identifier var: type_name
Example

Person type = Registration


name: chain
first name: chain
cin: integer
age: integer
address: string
END

31
var student: person
III. Access to a field of a record
The fields of a record type variable are accessible using the variable identifier and field name.

Example: student.name; student.address

Since the fields of a record correspond to a consecutive space of bytes, they act as variables. They
can thus be used in assignment, reading, writing, etc. actions.

Example : student.cin ← 02895275; read(student.name); write(student.name).

IV. Application example


Knowing that a complex number is defined by its real part and its imaginary part. Write an
algorithm to fill a table of complex numbers, calculate their sum and display the result on the
screen.

Answer

ComplexSum Algorithm
Const n=10
Complex type=Registration
re: real
im: real
END
var c: array[1..N] of complex
z: complex
i: integer
beginning
z.re ← 0
z.im ← 0
for i from 1 to N do
write(“Give the real part of the complex number “, i, “: “)
read(c[i].re)
write(“Give the imaginary part of the complex number “, i, “: “)
read(c[i].im)
z.re ← z.re + c[i].re
z.im ← z.im + c[i].im
end for
write(“the sum is: “, z.re, “+ i“, z.im)
END

32
Files
I. Concept of files
A FILE (English: file) is a LOGICAL GROUPING OF DATA STORED ON A PERMANENT
MEDIUM (hard disk, for example) in order to allow subsequent reuse of the information it
contains.

1. Structuring data in a file


The organization of data in a file is how the data will be organized within the file.

a. UNstructured files
We can list in this category all files such as documents, source codes, etc.

They are made up of a text so the structure is not determined: we do not find any notion of
elementary data. The file must be taken as a whole.

These files nevertheless include a format recognized by a program which will be able to analyze
its content and find meaning in it. (.docs are read by MS Word).

b. Structured files
Unlike the first, structured files are composed of a set of elementary data that can be precisely
identified within the file.

 Structure determined by elementary data markup : In this category, we will find files
of type XML, HTML, Latex, etc. Each elementary piece of data is framed by markup.
 Structure organized into records : A record is a block of elementary data that describes
an entity. For example, within a “Customers” file, a record corresponds to data relating to
a customer.

A field is one of the basic data of a record: the customer number is one of the fields of a record of
the customer file (others will be for example, the company name, the address, etc.) .

A record is therefore made up of several fields (field or item).

There are 2 ways to isolate fields in a record:

33
 Using a field separator character: the data is encoded in ASCII (or other character
format); a record corresponds to a line of a text file
 Using a precise definition of the record and its fields using a structured type.

2. Summary of file characteristics


Organization Unstructured Structured in grouping of elementary data
Data tagging
Delimitation Records
elementary
the fields
Field separators Structure
Data files in text
.xml, .html, format (ASCII Data files in
structure coding, for binary .bmp
.cpp, .doc
defined in example): .csv or format, data files
a DTD .tab (spreadsheet data
export)

II. Data files structured into records


1. Determining data fields
Number of Field length Field comment
fields delimitation
Records with fixed variable A separator Digital data is
separator character is encoded in
of fields defined for the binary
entire and therefore not
file readable
Records with fixed fixed Saving as a
type structured type
structure
Example of recordings from a text file with separator character “; »:

1,"Tim";"Burtley";"[email protected]"
2,"Max";"Ximum";"[email protected]"
Example of records of a file with a structured type:

000@Tim Burtley [email protected] 000çMax Ximum


[email protected]
2. Organization of data placement
The organization of data in a file determines how each record will be placed.

34
a. Sequential organization
In sequential files, records are stored consecutively in the order they were entered and can only
be played back in that order.

If you need a specific record in a sequential file, you must read all the records that precede it,
starting with the first.

b. Calculated organization
In calculated placement files, records are placed at a specific position in the file. This position is

 Either given as the order number of the recording in the file,


 Or calculated according to a placement algorithm applied to a key (we speak of random
placement, in English: random).

c. Indexed organization
In indexed organization files, at least 2 files are necessary for each managed file:

 the first file contains the data


 the second file contains an index table which at a value of a key of a record maintains the
position of the file at which it is located.

The key corresponds to one of the fields of the record allowing the identification of a unique
record within the file.

3. Modes of accessing records in a file


Access to records in a file is determined by the organization of that file.

a. Sequential access
Sequential access involves browsing the records in a file in the order in which they are stored. To
access a recording, you must have read all the recordings that precede it.

Sequential access is carried out in only one “direction”: the records are browsed from start to
finish, with no backtracking possible.

b. Direct access
Direct access allows individual access to each of the records in a file, by accessing them directly:

 Either through a placement order number;

35
 Either with a key.

Direct access allows you to access multiple records directly, regardless of where the record is
located in the file.

4. Ways to open a file


The opening mode of a file will determine the actions that we will be authorized to perform on
this file.

Opening mode Actions allowed


reading In reading mode, only access to the data will be authorized, without
possible modification of the content
writing In write mode, the file is emptied of its contents, and will only be
possible to write new records
addition In add mode, the data present in the file will be preserved, and it will be
possible to add new records
readind, writing In read/write mode, the data present in the file will be preserved, and it
will be possible to modify the content of certain records.

III. Algorithmic – sequential files


The algorithmic language (and most programming languages) provides the programmer with a
set of instructions for manipulating files.

1. Declaration of a FILE type variable


VAR file: FILE

2. Open a sequential file


file ← OPEN(file_name, opening_mode)
With Opening mode among: READ, WRITE, ADD

3. Read a file and test the end of the file


READ_FILE (file, list_of_variables)
FF(file)
returns TRUE if the end of the file has been reached (there are no more records to read)

4. Write to a file
WRITE_FICHIER (file, list of variables)
Data is added either from the beginning of the file or from the end (depending on opening mode).
36
5. Close a file
CLOSE(file)
6. Example program
Example program:

VAR f1, f2: FILE


num, last name, first name, email: STRING
BEGINNING
f1 ← OPEN("file1.txt", READ)
f2 ← OPEN("file2.txt", WRITE)
// first lecture
READ_FICHIER(f1, num, last name, first name, email)
WHILE (NOT FF(f1))
WRITE_FICHIER(f2, num, last name, first name, email)
// other readings
READ_FICHIER (f1, num, last name, first name, email)
FINTANTQUE
CLOSE(f2)
CLOSE(f1)
END
Program example 2

Record Type=Record
num: INTEGER
name: CHAIN
email: CHAIN
END
VAR f3: FILE
line: record
BEGINNING
f3 ← OPEN("file3.dat" , WRITE)
WRITE("enter number, name and email address")
READ(line.num, line.name, line.email)
WRITE_FILE(f3, line)
CLOSE(f3)
END

37
References _
Ballot, P. (2023, October 11). ALGORITHMIC INITIATION . Retrieved from Sidi Mohamed Ben
Abdellah University:
http://www.est-usmba.ac.ma/ALGORITHME/co/module_ALGORITHME_23.html

Bouchiha, D. (2019). Introduction to algorithms and programming in Pascal. Naama University


Center.

Dezécache, P. (2012). Files. In P. Dezécache, Introduction to algorithms.


http://www.weboplanet.com.

tahar, D.N. (2016). Algorithmic and programming. Mohamed Boudiaf University of Science and
Technology (Oran).

WayToLearnX. (2018, September 9). Difference between procedural and object-oriented


programming . Retrieved from WayToLearnX:
https://waytolearnx.com/2018/09/difference-entre-programmation-procedurale-et-
orientee-objet.html#google_vignette

Zampieri, K., & Rivière, S. (2018). Conditional [if] structures. Unisciel, algoprog.

38
Chapter 3 Search and sorting algorithms
Structuring data is essential to manipulate it in programs. However, you must know how
to find the data in these structures, this is the goal of search and sorting algorithms.

The problem is to find an element in a linear structure (array).

- item may not be present

- the element can be present in several places

- if the structure has several dimensions, each dimension must be searched

Intuitive technique: sequential search

- we traverse the structure in the “natural” order

- we stop at the end, or when we find the element

- sometimes we can stop sooner

sequential search
Sequential search: we stop when we find the element, or when we reach the end of the array.

// this function returns true if e is present in tab, false otherwise

function searchElement1( tab: array [1..N] of string, e:string):boolean;

var i: integer; find: boolean;

begin

i <- 0;

find <- false;

while (i < tab.length and not(find)) do

if (tab[i] = e) then

find <- true;

39
else

i <- i + 1;

end if

endwhile

searchElement1 := find;

end;

1. Variation: Finding the number of occurrences


This function returns the number of times e is present in tab function with return integer
function searchElement3(string tab[], string e): integer;

var i, nbOc: int;

begin

i <- 0;

nbOc <- 0;

while (i < tab.length) do

if (tab[i] = e) then

nbOc <- nbOc + 1;

end if

i <- i + 1;

endwhile

searchElement3 := nbOc;

end;

Optimization: if the table is sorted, we can stop “earlier”.

40
remark: there is only optimization if we find a stopping point “quickly enough”

Divide and conquer principle: we divide the data into different parts which we process separately

Example: to search for an element in an array, we cut it in two and search in each part.

This principle is useful:

- if we can run programs in parallel, it will take approximately half the time to search for the
element.

- if the array is sorted, you can only search for the element in one of the parts.

Search by dichotomy: the table is supposed to be sorted in ascending order and we are looking
for an element e in an table t

1. Principle of the algorithm:


0- we look at the element located in the middle of t:

1- if it is e it is won.

2- if it is greater than e, we search in the left half

3- if it is smaller than e, we search in the right half

Remarks :

- it can only work if the array is sorted

- we cut the table into two parts not necessarily equal in size

Example: find 490 in the following table of integers.

41
Note: we find 490 in 4 iterations, a sequential search would have required 11 iterations

// this function returns true if e is present in tab, false otherwise

// the tab array is assumed to be sorted in ascending order

function searchElement3(string tab[], string e): boolean

int i, j;

boolean find;

begin

find <- false;

i <- 0;

j <- tab.length-1;

while (i <= j and not found) do

if (tab[(j+i)/2] = e) then

find <- true;

else

if (tab[(j+i)/2] > e) then

j <- (j+i)/2 – 1

else

42
i <- (j+i)/2 + 1;

end if

end if

endwhile

searchElement3 := find;

end

7. Sorting an array
Problem: let it be an array of N integers arranged anyhow. We are trying to modify the table in
such a way that the integers are arranged in ascending order.
Several strategies can be used to solve the sorting problem.
 Sort by selection
 Bubble sort.
 Insertion sort.
 Quick sort (quick sort).
In what follows, we will see two strategies: selection sort, and bubble sort.
a. Sort by selection
In this case, sorting an array consists of putting element number 1, that is to say the smallest, in
the right position. Then, we put the next element in the right position. And so on, until the last
one.

Algorithm Sort_tab_by_selection
Var T: array [1..10] of integer
x, i, j: integer
Begin
For i from 1 to 10 Do
Write (“enter element in position “, i)
Read (T[i]);
EndFor
For i from 1 to 9 Do
For j from i+1 to 10 Do
If (T[i] > T[j]) Then
x ← T[i]
43
T[i] ← T[j]
T[j] ← x
end if
EndFor
EndFor
For i from 1 to 10 Do
Write (T[i])
EndFor
End .
b. Bubble sorting
The basic idea of bubble sort is to say that an array sorted in ascending order is an array in which
each element is smaller than the one that follows it.
TriBubbles algorithm
CONST size ←10
Var T: array [1.. size] of integer
x,i, j: integer
sort: boolean
Begin
sort ← false
x ← size
While (sort = false) do
sort ← true
For i from 1 to terminal-1 Do
If (T[i] > T[i+1]) Then
x ← T[i]
T[i] ← T[i+1]
T[i+1] ← x
sort ← false
End if
EndFor
terminal ← terminal -1
EndWhile
END

Test if an array is sorted in ascending order: we ensure that each box (except the last) has
smaller content than that of the next box.

function testSort1(integer tab[]) : boolean


int i;
boolean b;
begin
b <- TRUE;
for (i from 0 to tab.length-2 step 1) do

44
if (tab[i] > tab[i+1]) then
b <- FALSE;
end if
endfor
testSort1← b;
END

1. Bubble sort

Bubble sort: we move up the largest element by permutation and start again until the array is
sorted.
Example: sort the following table in ascending order

17 2 268 415 45 45 102 701


2 17 268 45 45 102 415 701
2 17 45 45 102 268 415 701
2 17 45 45 102 268 415 701

Remarks :
- bubble sorting is in place. It is stable if we only permute the different elements.
- we could bring up the smallest element.
- we could stop as soon as the array is sorted
the sorting is stable, it would not be stable if we had put tab[j] >= tab[j+1]
2. Sort by selection
Sort by selection (selection sort): we go through the array to find the largest element, and once
we reach the end of the array we place this element there by permutation. Then we start again on
the rest of the table.

Selection sorting only performs one permutation to bring up the largest element at the end of the
array, so it is more efficient than bubble sorting.

Sort selection is in place and the algorithm given here is stable. It would be unstable if we
replaced the comparison tab[j] > tab[pg] with tab[j] >= tab[pg].

Selection sorting can be improved by positioning the largest and smallest element on each
journey through the array, according to the same principle as that used for boustrophedon
bubble sorting.

3. insertion sort

Sorting by insertion (insertion sort): we take two elements which we sort in the correct order,
then a 3rd which we insert in its place among the 2 others, then a 4th which we insert in its place
among the 3 others , etc.

45
procedure sortInsertion(var tab: Array [1..N] of integer);
var i, j, val:integer;
begin
for (i from 1 to tab.length-1 ) do
val <- tab[i];
j <- i;
while ((j > 0) and (tab[j-1] > val)) do
tab[j] <- tab[j-1];
j <- j-1;
endwhile
tab[j] <- val;
endfor
end

46

You might also like