0% found this document useful (0 votes)
9 views

Algorithms and Data Structure

The document discusses computer science and algorithms. It defines key concepts like algorithms, data structures, variables, constants, and basic instructions. The document provides examples to illustrate these concepts.

Uploaded by

ayobkoko55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Algorithms and Data Structure

The document discusses computer science and algorithms. It defines key concepts like algorithms, data structures, variables, constants, and basic instructions. The document provides examples to illustrate these concepts.

Uploaded by

ayobkoko55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Amar Telidji University

Laghouat

Department of Computer science

Algorithms and data structures


1st Year M.I. L

Tahar ALLAOUI
[email protected]
Please inform me of any errors
in this document
Chapter 1: General
introduction
Chapter 1: General introduction

1. Introduction
Nowadays, computing technology touches all areas of our daily lives. Thanks to the
advantages it offers, it made it possible to carry out difficult and even complex tasks quickly
and easily.

2. Definitions
2.1 Computer science

Computer science is the science of automatic processing of information by a machine called a


"Computer".

Information Information

(Data) (Results)
Treatment (Processing)
Input Output
2.2 Computer Computer

The computer is an electronic machine used to solve problems by executing instructions. It is


a set of peripheral devices that communicate with each other to carry out a given task.
2.3. The benefits of using computers
Computers are used to solve a wide range of problems in a short space of time.
How can this be done?
An important question is how to explain to the computer how to solve a given problem.
To answer this question, examples are given of how simple everyday problems are solved.
Example 1: Send an SMS to someone:
To send an SMS, the user must perform the following actions:
1. Click on "Menu
2. Go to "Messaging
3. Select "New message
4. Edit the message
5. Write the recipient number
6. Click on the "Send" button
This example shows the steps of sending an SMS, consisting of an ordered sequence of

4
Chapter 1: General introduction

actions represented as commands or instructions (Click, Give, Edit, Choose, etc.) that
manipulate data (Menu, Messaging, Recipient number, etc.) to perform the desired task
(sending an SMS).

Example 2: Calculate the solutions of a 2nd degree equation:


To solve this problem, we apply the following steps:
1. Give the values of: a, b, and c.
2. Calculate the value of Delta
3. Calculate the values of the solutions according to the value of Delta.
Similarly, in this example, we manipulate data (a, b, c) through an ordered sequence of
instructions (Calculate Delta, Calculate solutions,...) to find the solutions to the equation.
Clearly, solving a problem requires the application of a sequence of actions on a set of data in
a well-defined order to achieve the result.
For a computer to solve a problem, we need to "explain" the actions to be applied and the data
to be manipulated. This explanation, which represents the solution to the problem to be
solved, will be presented in the form of actions (also called commands or instructions) which
manipulate a set of data.
The set of instructions and manipulated data together form an algorithm.
3. Definition of an algorithm
An algorithm is an ordered sequence of instructions (actions, commands) which indicate the
steps to be taken to solve a given problem.
In an algorithm, the order of instructions is important and has a major influence on the
obtained result.
The word Algorithm is of Arabic origin, and comes from the name of : Al Khawarizmi (780-
850), the Muslim scholar considered to be the father of algebra.
4. Algorithms science
The science of algorithms is a set of rules and techniques used in the design and definition of
algorithms.
5. Description language of algorithms
This is a universal language that is very close to natural language, and enables algorithms to
be written in a way that is readable and understandable by users. It's a rich, machine-free
language, offering the possibility of correction and modification.
6. Flowchart
5
Chapter 1: General introduction

A flowchart is a graphical representation of an algorithm that makes it easier to understand.


Each type of instruction has its own graphic form.
7. Program
This is the translation of an algorithm into a particular programming language.
The set of instructions for a program is called source code.
Execution of a program (source code) by the computer produces an executable program,
which manipulates the various problem data to produce the desired results.
8. Programming
Programming is the set of activities involved in writing programs, i.e. writing the source code
for a program.
9. Programming language
A set of vocabularies and well-defined rules enabling programmers to write programs that
will be executed by the computer.
10. Programming language types
10.1. Machine language
Also known as machine code, this is a level 0 language that can be understood by the
machine, and whose form is in binary.
10.2. Assembly language
Also called assembly language or simply assembler, this is a low-level language that
represents machine language in human-readable form.
10.3. Advanced languages
Also known as high-level languages, these are languages with a rich vocabulary, easy to
understand and maintain, and well-defined writing rules.

6
Chapter 2:
Data structures
and basic instructions
Chapter 2: Data structures and basic instructions

1. Introduction
In order to solve various problems in computer science, we use programs that are
understandable and executable by the machine, but before moving on to programming, we
must first represent the solutions in the form of algorithms.
It's true that an algorithm is only a representation of the solution, written in a universal
language, but this algorithm has a well-defined general form, and its writing must respect
rules to make easythe transition to programming.

2. General structure of an algorithm


Generally, an algorithm has the following structure:
Algorithm Name of the algorithm } Header
Declarations } Declaration part
Begin
Instruction 1 ;
Instruction 2 ; Body of the algorithm

Instruction n ;
End.
 The header: each algorithm must have a name that identifies it in the header.
 Declarations: in an algorithm, we manipulate the problem data to obtain results, the
declaration part contains the list of used data in the algorithm as well as their natures.
 The body of the algorithm: this is the part that represents the work carried out by the
algorithm; all the instructions and operations executed by the algorithm are found in
this part.
3. Header
This part contains the name (identifier) of the algorithm. This name must be a sequence of
letters and numbers, starting with a letter and containing no spaces.
4. The declaration part
The used data in the algorithm must be defined (declared) to facilitate their manipulation. To
do this, we need to use data structures.
5. Data structures
Definition: A data structure is a logical structure designed to hold data. It is a logical medium
for storing data.

9
Chapter 2: Data structures and basic instructions

Each data structure is characterized by :


1. An identifier: this is the name of the data structure, made up of letters and numbers.
The name must follow the same rules as the name of the algorithm, e.g. x1, y2,
tab,...represent data structure identifiers.
2. A type: Each data structure has a type that indicates the nature of the information
stored in that data structure. There are five basic types:
Integer: a sequence of digits which may be preceded by a sign (+ or -).
Real: a sequence of digits that may be preceded by a sign, and may contain a decimal
point.
Boolean: data with only two possible values: true or false.
Character: 'a'...'z', 'A'...'Z', '5', '!', '?', '@'.
String: a concatenation of several characters, for example: 'computer '.
3. A value : this indicates the value of the data in the data structure during the execution
of an algorithm; this value can be fixed or variable.
Note: depending on the value of the data structure (fixed or variable), there are two main
families of data structures: constants and variables.
5.1. Constants
A constant is a data structure whose value is fixed and does not change throughout the
algorithm.
Declaring constants
To declare a constant, use the keyword const in the declaration section.
Example:
const X=2 ;
Y= 'good day' ;
X is an integer constant whose value is 12.
Y is a string constant whose value is: good day.
5.2. Variables
A variable is a data structure whose value is variable and can be changed within the
algorithm.
Declaring variables
To declare variables, use the keyword var in the declaration section.
Example:
var P1 : Boolean ;
a, b, c : real ;

10
Chapter 2: Data structures and basic instructions

P1 is a boolean variable
a, b and c are real variables.
Note that variable values are not defined in the declaration section; the value of a variable is
given in the body of the algorithm.
6. The body of the algorithm
This body section contains all the instructions and operations performed by the algorithm. In
the body of the algorithm are the instructions that give values to the various variables and
other instructions that represent the steps to be taken to solve the problem. Therefore, it is
important to respect a well-defined order between these instructions in order to reach the
solution.
7. Basic instructions
7.1. Input-output instructions
The algorithm needs input data to provide output results. To achieve this, it uses input-output
instructions, which enable users to input information and receive other information.
Reading data
This instruction allows the user to set the value of one or more variables. The value entered by
the user will be stored in the concerned variable.
There are several forms of the read instruction:
1.Read a single item of data: read (variable name) ;
Example: read(X)
This instruction assigns the value given by the user to variable X. If the user types 10, for
example, variable X will have the value 10.
2.Read multiple data: read (variable1, variable2, ...)
Example: read (X,Y, Z) ;
This instruction assigns the values given by the user to variables X, Y and Z in this order: if
the user gives 4, 9 and 11 in this order, then X will have the value 4, Y will have the value 9
and Z will have the value 11.
Note: when performing a read operation, the user must give a value of the same type as the
variable, otherwise an error will occur.
Writing data
This instruction is used to display data on the screen. Depending on the nature of the
displayed data, several forms can be distinguished:
Display the value of a variable: write (variable name) ;

11
Chapter 2: Data structures and basic instructions

Display a text: write ('Text to display') ;


Display text and values: write ('Text to display', variable, 'Text to display', variable,...) ;
Note: Input-output instructions are represented in the flowchart by the following symbol:

7.2. Expressions
Variables and constants are manipulated in algorithms using expressions.
Definition: An expression is a combination of operands (variables or constants) and
operators.
Depending on the types of operands and operators, we can distinguish two main families of
expressions: arithmetic expressions and logical expressions.
Arithmetic expressions
An expression whose operands are numeric (integers or reals); and whose operators are
arithmetic.
Logical expressions :
A logical expression can be a combination of logical operands and logical operators, or it can
be a combination of numerical operands and comparison operators.
7.3. Assignment
It is an instruction used to assign a value to a variable. In other words, the assignment
instruction fills the logical support with a value given by the user or calculated by an
expression.
General forms of the assignment instruction
1. Var ← Fixed value, in which case the variable takes the value.
Example: X ← 17; reads: X receives 17
2. Var1 ← Var2
The variable Var1 takes the value of Var2 without changing the value of Var2.
Example: X ← Y
3. Var ← expression
The variable takes the value of the result of the expression after its evaluation.
Examples

12
Chapter 2: Data structures and basic instructions

● nbr ←3+5-4 (the variable nbr receives the value 4)


● P1← true and false (variable P1 receives the value false)
Remarks:
 In this form, the variable and the result of the expression must have the same type.
 In an algorithm, many values can be assigned to a variable several times; the new
assignment will overwrite the old value.

8. Exercise
Write an algorithm to display the sum of two integer values given by the user, and give the
flowchart corresponding to this algorithm.
8.1. Analysis
In this algorithm, the user will give two integer values, so we need two integer variables to
store the values.
A third variable must also be used to store the result of the addition.
The result must be displayed.
8.2. The algorithm
In this algorithm, we use a variable nbr1 for the 1st value, and a variable nbr2 for the 2nd
value. We also use the variable result for the result
Therefore, the algorithm will be :
Algorithm Sum ;
var nbr1, nbr2, result : integer ;
Begin
read (nbr1, nbr2) ;
result ← nbr1 + nbr2 ;
write (result) ;
End.

8.3. The flowcharts


A flowchart is a graphical representation of an algorithm to make it easier to understand.
Notes :
 Begin and end keywords are represented by rectangles with rounded corners.
 Expressions and assignments are represented by rectangles.
The corresponding flowchart to the previous algorithm will be :

13
Chapter 2: Data structures and basic instructions

Begin

Read(nbr1,nbr2
)

result ← nbr1 + nbr2

Write (résult)

End

14
Chapter 3 : Conditional
instruction
Chapter 3 : Conditional instruction

1. Introduction
Up to now, we've seen algorithms that follow a single path to solve a problem, i.e., algorithms
that execute instructions sequentially without breaking, this structure of algorithms is called
the linear structure.
In this chapter, we'll discover a new structure that allows instructions to be executed
according to a choice, in which case the algorithm structure becomes an alternative structure.
To understand the usefulness of this structure, we give the following examples.
Example 1: Write an algorithm that calculates the average for a student with three modules.
The solution to this problem is simple: we need to read the module grades, then calculate the
average of these grades, so the corresponding algorithm will be :
Algorithm Average;
Var n1, n2, n3, moy :real ;
Begin
Read (n1, n2, n3) ;
moy← (n1+n2+n3)/3 ;
write (moy) ;
End.

Example 2: Write an algorithm that calculates a student's average, and displays "admitted" if
the student's average is greater than or equal to 10.
Note that the display of "admitted" depends on the average value, and that the display
instruction can only be executed once a condition has been checked.
To do this, we need to use a new instruction: the conditional instruction.

2. Conditional instruction
It is an alternative instruction, which consists of executing one or more instructions after a
condition has been checked.
The condition must be a logical expression; this is why it's called a logical test.
3. The different forms of conditional instruction
3.1. The 1st form: The reduced conditional statement
If condition then
Actions ;
End if

17
Chapter 3 : Conditional instruction

If the condition is verified (its value is true), we execute the actions, then continue executing
the algorithm. Otherwise (the condition value is false), we directly execute the instructions
that follow the "end if" without executing the actions.
The Flowcharts
In flowcharts, conditional instructions can be represented as follows

Condition
True

Actions

The algorithm corresponding to the previous example


Algorithm Average ;
Var n1, n2, n3, moy :real ;
Begin
Read (n1, n2, n3) ;
moy←(n1+n2+n3)/3 ;
If moy>=10 then
write ('Admitted') ;
end if
write(moy) ;
End.

Example 3: Write an algorithm that displays Admitted if the average is greater than or equal
to 10, and displays Adjourned if this is not the case.
In this case, the reduced conditional statement doesn't solve the problem because we have two
possibilities, so we need to use a new form of the conditional statement

18
Chapter 3 : Conditional instruction

3.2. The 2nd form: The complete conditional statement


If condition then
Action 1
Else
Action2 ;
End if
If the condition is verified, only action1 is executed, then action2 is skipped to execute the
rest of the algorithm after the "end if".
If the condition is not verified, action1 will be skipped, and only action2 will be executed.
The flowchart
The complete conditional instruction is represented in flowcharts by the following form

False True
Condition

Action 2 Action 1

The algorithm for example 3


Algorithm Average ;
Var n1, n2, n3, moy : real ;
Begin
Read (n1, n2, n3) ;
moy← (n1+n2+n3)/3 ;
write (moy) ;
if ( moy>=10) then
write ('Admitted')
Else
write ('Adjourned') ;
end if
End.

19
Chapter 3 : Conditional instruction

Example 4: Write an algorithm which reads a number given by the user, then displays
'positive', 'negative' or 'null' depending on the value of this number.
Clearly, we need to use a conditional instruction to solve this problem, but in the complete
conditional statement the condition can have only two values, i.e., we can handle only two
cases, but in this problem, we have 3 cases to handle, so we need to use several conditional
instrucions
3.3. Nested conditional instructions
If condition1 then
Action1 ;
Else
if condition 2 then
Action2 ;
Else action3
End if
End if
The algorithm of Example 4
Algorithm Number
Var nbr : integer ;
Begin
Read (nbr) ;
If (nbr>0) then
Write ('positive')
else
If nbr<0 then
write('negative')
else write('null') ;
end if
end if
End.

3.4. The choice instruction


In some algorithms, there may be several nested instructions, making the algorithm difficult to
understand and manipulate.

20
Chapter 3 : Conditional instruction

To avoid this, we use another form of conditional instruction which is the choice instruction
Case. This instruction consists in checking only one variable (integer, character, Boolean),
and executing actions according to its possible values.
The general form of the choice instruction
Case variable of
Value 1: Action 1 ;
Value 2: Action 2 ;
Value3, value 4: Action3 ;
Value 5..value6 : Action4 ;
Otherwise Action n
End Case ;
We compare the variable with value 1, if there is a tie, we execute action 1, and exit the
instruction, otherwise, we compare the variable with value 2, we execute action 2 if there is a
tie and exit, otherwise, we compare with value3, and so on, if the variable value is different
from all the values, we execute action n.
Remarks
 The form Value1, Value2, Value3: Action: This means that several different values
can cause the same action to be executed.
 The form Value1..Value2 : Action : Means that the action must be executed with all
the values in this interval.
Example: Write an algorithm that displays the number of days in a month given by the user
Algorithm month ;
Var m :integer ;
Begin
Read(m) ;
Case m of
1, 3, 5, 7, 8, 10, 12 : write('the number of days is 31') ;
4, 6, 9, 11 : write('The number of days is 30') ;
2: write ('the number of days is 28') ;
Otherwise write ('Error') ;
End Case ;
End.
Note: In this algorithm we have assumed that the number of days in February is always 28.

21
Chapter 4: Loops

22
Chapter 4: Loops

1. Introduction
When a processing operation has to be carried out several times in the algorithm, it is not
practical to rewrite a block of instructions several times in the algorithm.
So we need to find a way to avoid writing the same instruction several times in the same
algorithm, but which also allows its execution to be repeated. This is why we use loops.
2. Loops
A loop is an action that allows you to repeat the execution of one or more instructions without
having to repeat the writing several times.
Two types of loop can be distinguished, depending on the number of times the instructions are
repeated:
2.1. The number of repetitions is known in advance: The For loop
In this loop, the number of repetitions is known in advance, so we use a counter that varies
between an initial value and a final value. This counter represents the loop's control variable;
when the counter reaches the final value, the loop stops automatically.
The general form of the loop for
For variable :=initial value to final value
Do
Instructions
End for
Properties
 Each pass through the loop instructions is called an iteration.
 The number of iterations is known in advance:
 The number of iterations = final value - initial value +1.
 The execution of the loop instructions precedes the verification of the stop condition,
so there is at least one execution.
Example
Write an algorithm to calculate the factorial of a positive integer
Algorithm Factorial;
Var fact, n, i : integer ;
Begin
Read(n) ;
fact ← 1 ;

23
Chapter 4: Loops

For i=1 to n do
fact ← fact * i ;
end for
write (fact) ;
End.

2.2. The number of repetitions is not known in advance


To be able to execute a loop without needing to know the number of repetitions in advance,
we must avoid using a counter. In this case, the loop repetition depends on the value of a
condition; when the condition value is changed, the loop stops.
Two loops can be used in this case:
1. The loop While
In this loop, the repetition of instructions depends on a condition. As long as the condition is
verified (its value is true), the loop instructions are executed again.
The general form of the loop While
While condition
Do
Instructions
End
Note: it's clear that the condition must be a logical expression.
Properties
 In this loop, the number of iterations must not be known in advance.
 The condition is checked before the loop is executed. If the condition is not checked,
the loop is exited, so the minimum number of iterations may be 0.
 On exiting the loop, the loop condition is always false.

2. The loop Repeat ...until


In this loop, instructions are repeated when the value of the condition is false. Once the
condition is verified (its value becomes true), we exit the loop.
The general form
Repeat
Instructions;
Until Condition

24
Chapter 4: Loops

Properties
 In this loop, the number of iterations must not be known in advance.
 The condition is checked after the instructions have been executed, so there is at least
one execution of the loop instructions.
 When the loop exits, the stop condition is always true.
Important note!
We must ensure that loop iterations allow to modify the value of the loop condition, otherwise
the loop will never stop, resulting in an infinite loop and a computer crash.

Comment choisir la boucle à utiliser dans un algorithme ?


Le choix de la boucle se fait selon la nature du problème :
● Si le nombre de répétition est connu, on utilise donc la boucle Pour
● Si le nombre de répétition n’est pas connu, mais on a au moins une exécution, on
utilise la boucle Répéter
● Si le nombre de répétition n’est pas connu, et peut même être zéro, on doit utiliser la
boucle Tant que.

Remarque :n’importe quelle boucle Pour peut-être remplacée par la boucle Tant que ou
Répéter, mais l’inverse n’est pas toujours vrai.
How do you choose which loop to use in an algorithm?
The choice of loop depends on the nature of the problem:
 If the number of repetitions is known, the loop For is used.
 If the number of repetitions is not known, but we have at least one execution, we use
the loop Repeat.
 If the number of repetitions is not known, and may even be zero, use the loop While.
Note: any loop For can be replaced by the loop While or the loop Repeat, but the reverse is
not always true.

25
Chapter 5: Arrays

26
Chapter 5: Arrays

1. Introduction
When writing algorithms, we can manipulate variables and constants of different types, and
we can declare as many variables as we need to solve different problems.
It may be that in a given algorithm, we need to manipulate 100 variables of the same type,
such as the calculation of student averages. Therefore, It is possible to declare 100 variables
of real type.
Such an algorithm is impractical, and handling a large number of variables is very difficult; so
we need to find a way to easily manipulate a large number of data of the same type.
The solution is to use a new data structure: Arrays.
2. Arrays
2.1. Definition
An array (also known as a vector) is a complex data structure used to group together data of
the same type. These data all have the same name (the name of the array), the same type, and
can have different values.
2.2 Array elements
Each piece of data in an array is called an array element.
An element is characterized by its name (the name of the array), a type (the type of the array),
and a value.
Each element is identified by an index (a rankn, a position) which indicates its position in the
array.
2.3. The dimension of an array
The dimension (or size) of an array refers to the number of elements in the array.
2.4. Declaring an array
An array is a variable with a name, a dimension and a type that represents the type of all its
elements. The general form of an array declaration is given below:
Var array name: Array [1..Dimension] of type ;
Example
Var Tab : Array [1..5] of integers ;
Tab is an array of five integer elements, and we can imagine its form like this:
12 -5 3 0 29

27
Chapter 5: Arrays

2.5. Accessing an element in an array


To access an element in an array, we need to enter its index, i.e. the array name followed by
the element's position in the array.
Example
Tab [1]: the 1st element in the array
Tab [2]: the 2nd element in the array
...
Tab [N] : the last element of the array, where N is the array dimension.
Notes:
 Each array element can be processed independently of the others.
 The possible operations with an array element are all the possible operations with the
type of this element.
3. Exercise
Let T be an array of three integer elements.
Give the algorithm that displays the sum of the elements in this array.
Algorithm Sum ;
Var T : array [1..3] of integers ;
S : integer ;
Begin
Read ( T[1], T[2], T[3]) ;
S← T[1] +T[2]+T[3] ;
Write (S) ;
End.

4. Two-dimensional arrays
A two-dimensional array (matrix) is very similar to a set of concatenated vectors. Each
"vector" represents a row in the matrix, and all cells of the same rank represent a column in
the matrix. The following figure shows a matrix with 7 rows and 10 columns.

28
Chapter 5: Arrays

4.1. Dimensions of a matrix


A matrix is characterized by two dimensions: the first dimension designates the number of
rows in the matrix, and the second dimension designates the number of columns.
Note : In a matrix, all rows have the same number of cells.
4.2. Declaring a matrix
A two-dimensional array is a variable with a name, and a type that represents the type of all
its elements. The general form of an array declaration is given as follows:
Var array name: Array [1..Number of rows, 1..Number of columns] of type ;
Example
Var tab : Array [1..3,1..4] of integer ;
Tab is an array of three rows and 4 columns, whose elements are of integer type.
4.3 Matrix elements
An element in a matrix is characterized by its name (the name of the array), a type (the type of
the array), and a value.
Each element is identified by two indices: one indicating the row number, the other the
column number.
To access an element in the matrix, you need to specify the row number and the column
number.
Example
Tab[1,3] : represents the element in row 1 and column 3
4.4. The square matrix
The square matrix is a special matrix whose number of rows is the same as the number of
columns.
The declaration of a square matrix can be given as follows:
Var Mat : array [1..n, 1..n] of integers;
4.5. Manipulating matrices using loops
In general, manipulating matrices with loops requires two nested loops, as you need one loop
to move from row to row, and another loop to move from column to column.
Depending on the locations of the loops, we'll have two processing modes:
If the loop that varies the row index is the outer loop, the matrix is manipulated row by row,
since each change of a row index changes all the column indices.
If the loop that varies the column index is the outer loop, the matrix is manipulated column by
column, since each change of a column index changes all the row indices.

29
Chapter 5: Arrays

Example
Let's take the example of writing a Tab matrix with N rows and M columns. The elements of
this matrix can be written in two different ways
… …
For j := 1 to M
For i := 1 to N
Do
Do
For i :=1 to N
For j :=1 to M
Do
Do
Write (Tab [i , j ]) ;
Write (Tab [i , j ]) ;
End for
End for
End for
End for….
….
The matrix is written line by line The matrix is written column by column.

4.6. exercise
Let Mat be a matrix with 3 rows and 5 columns whose elements are integers. Give the
algorithm for displaying the sum of the elements of this matrix.
Algorithm Sum_matrix ;
Var Mat : array [1..3, 1..5] of integers ;
i, j, S : integer ;
Begin
For i := 1 to 3
Do
For j :=1 to 5
Do
read (Mat [i , j ]) ;
End for
End for
S := 0 ;
For i := 1 to 3
Do
For j :=1 to 5
Do
S := S + Mat [i , j ] ;
End for
End for
Write ('The sum of the elements of this matrix is:', S) ;
End.

30

You might also like