Course Algo Ch1 Ch2 Part1 2023 Cne2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University

Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

Abdelhamid Mehri – Constantine 2 University


2022-2023. Semester 1

Introduction to algorithms

Chapter 1 & 2 : Introduction and Basic Concepts

Chargé de cours
Name Grade Faculty/Institute E-mail
mail address
BADECHE Mohamed MCB New technologies algo.assistance@gmail.com
o.assistance@gmail.com

Etudiants concernés
Faculty/Institute Department Year Speciality
New technologies MI License 1 Common Core

Objectives :
Introduce the concept of algorithm.
State syntactic conventions.
Become familiar with the basic instructions.
instruc
Getting started with conditional and repetitive processing.
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

Sommaire
Chapter 1: Introduction .......................................................................................................................................................... 1
1.1. Components of a computer ......................................................................................................................................... 1
Chapter 2: Algorithm .............................................................................................................................................................. 2
2.1. Introduction to the concept of algorithm .................................................................................................................... 2
2.1.1. Simple examples of program execution ............................................................................................................... 2
2.1.2. Algorithm example................................................................................................................................................ 3
2.1.3. Definition of an algorithm..................................................................................................................................... 3
2.1.4. Structure of an algorithm ..................................................................................................................................... 4
2.1.5. Basic instructions (‘Read’, ‘Write’ and assignment) ............................................................................................. 4
2.1.6. Algorithm vs Program ........................................................................................................................................... 5
2.1.7. User vs Programmer (Developer) ......................................................................................................................... 5
2.1.8. Basic syntactic conventions .................................................................................................................................. 5
2.1.9. Manual execution of an algorithm ....................................................................................................................... 6
2.1.10. Comprehension questions .................................................................................................................................. 7
2.1.11 Exercises............................................................................................................................................................... 8
2.2. Equivalent algorithms .................................................................................................................................................. 9
2.2.1. Optimal (best) algorithm ...................................................................................................................................... 9
2.2.2. Indicative and explanatory messages ................................................................................................................... 9
2.2.3. Questions de compréhension ............................................................................................................................. 10
2.2.4. Exercises.............................................................................................................................................................. 10
2.3. Types of variables ...................................................................................................................................................... 11
2.3.1. Exercise ............................................................................................................................................................... 12
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

Chapter 1: Introduction

1.1. Components of a computer


The word computing is made up of the two terms: information and automatic. Computer science is the science
of automatic information processing.
Computer science can be seen in two aspects: hardware and software.
The following diagram summarizes the hardware and software components of a computer:

Computer science

Hardware Software

Central Unit (CPU) Peripheral devices Operating systems Programs

Keyboard Mouse Word Calculator


Motherboard Windows Linux
Screen Paint
Microprocessor Memories Mac Os
I5 2.5 GHz

RAM Hard Disk


(Volatile) (Permanent)
8 GO 500 GO

1
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

Chapter 2: Algorithm

2.1. Introduction to the concept of algorithm


In order to introduce the notion of algorithm, we will present two very simple programs and describe their
executions on a machine.

2.1.1. Simple examples of program execution


Consider the following two simple programs, the first in Visual Basic and the second in C language. The
following table describes the execution, from the user's point of view, of the two programs on the machine, step
by step:

Description of
Running a program in Visual Basic (VB) Executing a program in C language
execution steps
Private Sub Form_Load() int main()
{
Dim a, b, c As Integer int a, b, c;
a = InputBox("") scanf("%d",&a);
Program code
b = InputBox("") scanf("%d ",&b);
c=a*b c = a*b;
MsgBox (c) printf("%d", c);
End sub }

The program displays


the cursor to allow
the user to enter a
value

The user enters the


value: 100

The program displays


the cursor again

2
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

the user enters a


second value: 5

The program displays


the result of
multiplying the two
values entered by the
user: 500

2.1.2. Algorithm example


An algorithm is the equivalent of a program, it is written in pseudo code (an algorithm is a draft of a program).
Pseudo code is located between natural language and codes written in programming languages, it is close to
programming languages in their formalisms, but less strict in its writing rules. The following algorithm is the
pseudo code equivalent of the two programs in the previous section:
Visual Basic code C code C++ code Pseudo Code
Private Sub Form_Load() main() main() Algo Exo1 Head
{ {
Dim a, b, c As Integer int a, b, c; int a, b, c; Var Statement
a,b,c: Integer
Begin Announce start of instructions.
a = InputBox("") scanf("%d",&a); cin >> a ; Read(a) Allow the user to enter the value
of a.
b = InputBox("") scanf("%d",&b); cin >> b ; Read(b) Allow the user to enter the value
of b.
Multiply a by b and put the result
c=a*b c = a*b; c = a*b; c a*b
in c.
MsgBox (c) printf("%d", c); cout >> c ; Write(c) Show result stored in c.
End sub } } End Announce the End.

2.1.3. Definition of an algorithm


The word algorithm comes from the name of Al-Khwarizmî ( ‫ارز‬ ‫)ا‬, great mathematician of the 9th century.
Definition 1: An algorithm is a finite and unambiguous sequence of operations or instructions used to solve a
problem1.
Definition 2: An algorithm is a general method for solving a type of problem. It is said to be correct when, for
each instance of the problem, it ends producing the correct output. That is to say it solves the problem posed1.
Definition 3: An algorithm is simply a way of describing down to the smallest details how to proceed to do
something2.

1
Wikipedia
2
Philippe Flajolet, Étienne Parizot, « Qu'est ce qu'un algorithme ? », interstices.fr, 2004.
3
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

2.1.4. Structure of an algorithm


The algorithm generally consists of three blocks:
Algo Exo1 Header
Var
… Declarations
Begin
… Body (Sequence of instructions)
End
1. In the header block, we give a name to the algorithm. This name can be composed of letters and numbers
and must begin with a letter, and must not contain punctuation letters, in particular spaces.
2. In the declaration block, we declare the types of variables used. A variable is the association of an identifier
(a variable name) with data. A variable can be of the type Integer like the introductory example, Real like
the example in section 2.1.5, Character and string like the example in section 2.3, and other types that we
will see as we go on. and as you progress in this course.
3. The body block contains the instructions themselves, to be executed in order.

2.1.5. Basic instructions (‘Read’, ‘Write’ and assignment)


In almost all algorithms, we find the three basic instructions: the Read instruction, the Write instruction and
the assignment instruction.
- The Read instruction gives control (allows) the user to enter one or more data.
- The Write instruction allows you to display (print) results or messages on screen.
- The assignment instruction ( ) allows you to save (store) a value in a variable.
Example :
Consider the following algorithm which allows you to calculate the area (surface) of a circle from its radius.
Algo Area
Var
R, A : Real
Begin
Read(R)
A 3.14 * R * R
Write(A)
End
Note that the type of variables declared in this algorithm is Real, since the radius can be in comma like 2.5, and
the result is necessarily in comma due to the multiplication by 3.14.
This algorithm allows you to:
1. Give the user hand to enter an actual value for the radius of a circle.
2. Calculate the area (surface) from the formula πR2, and store the result in the variable A through the
assignment instruction ( ) which we read: receives (A receives 3.14 times R times R).
3. Display the result (the calculated area of the circle).
The Read instruction can give control to the user to enter multiple values. The following two entries are
correct:
Read(a)
Read(a,b)
Read(b)

4
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

The assignment instruction always has a variable in its left part and can have in its right part, either a constant
(A 3.14), or a variable which has a value (A B), or an evaluable expression (A B*2+3). Writings like:
3.14 A, A + 2 B and A B 5 are syntactically incorrect.
The Write instruction displays either variable values: Write(A), or messages: Write("Hello"), or a combination
of messages and variables: Write("the area of the circle is ", A, " cm2").
By convention in this course, the Write instruction displays and jumps to the next line.

2.1.6. Algorithm vs Program


The aim behind writing an algorithm is to transform it (translate it) into a program executable on a machine.
Algorithmic pseudo code allows you to write algorithms by hand in order to focus on ideas and reasoning, it is
not supposed to be executed directly on a machine, except after having transformed (translated) it into code
written in a programming language like C language, Visual Basic, Java, Python…
So it is the algorithm that was created in the service of programming and not the other way around.

Algorithm Program
Pseudo code Code
Not directly executable on machine 3 Executable directly on machine
It was created for the programming service

2.1.7. User vs Programmer (Developer)


We must distinguish the two roles: user and programmer. A programmer (or developer) designs programs
intended for use by users.
When we write algorithms, we play the role of programmer who writes an algorithm in order to subsequently
transform (translate) it into an executable program. The user, for his part, does not see the sequence of
instructions that a programmer has written, but only sees the inputs (that the programmer asks him to give) and
the outputs that the programmer displays to him. For him, what happens between inputs and outputs is a black
box.

Inputs Outputs
Treatment

The programmer must sometimes put himself in the user's shoes to test his program himself, and thus plays
both roles.

2.1.8. Basic syntactic conventions


The pseudo code is purely conventional4, which means that we have the possibility of defining the conventions
that we consider appropriate, while trying, as far as possible, to keep those that are the most common.
These rules are imposed mainly to remove ambiguity and teach rigor, they are not required in themselves.
Rather, it is logic and algorithmic reasoning that are at the center of this course.
We can summarize the basic conventions that we will adopt throughout the year as follows:

- We can put several instructions on the same line separated by a semicolon (but we prefer to put one per line).

3
The case of applications like 'AlgBox' on PC or 'Algo' on Smartphone, which in appearance allow you to execute algorithms, are in
reality only educational tools for simulating the execution of an algorithm on a machine.
4
« Algorithmique et programmation pour non-matheux », Christophe Darmangeat, 2013, Université Paris 7,
http://pise.info/algo/introduction.htm
5
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

- There is no distinction between upper and lower case for keywords. We can write for example: BEGIN, Begin
or begin.
- There is a distinction between upper and lower case letters for variables. The two variables: Name and NAME
are distinct (although this point is not considered in the correction of the final exams of this course).
- The name of the algorithm and variables can be composed of letters and numbers and must begin with a letter,
must not contain indices and punctuation letters, in particular space. We can write ex_01 as the algorithm name
and not ex 01.
- Blanks and tabs before instructions are allowed, as do before and after variables, commas and parentheses.
The extra line breaks also are allowed.
- Semicolons at the end of instructions are not required.
- Parentheses are required in both Read and Write instructions. For example, we write Read(a) and not Read
a.
- Messages that appear in the Write instruction must be delimited by " (double quotes) on both sides, such as:
Write("Hello").
- Variable types must be singular. We write: Integer, and not Integers.
- You can put several instructions on the same line (but we prefer to put one per line).
- The basic adopted keywords are:
o Algo ou Algorithm
o Var ou Variables ou Variable
o Begin
o End
o Read
o Write
o Integer
o Real
o Char ou Character
o Str ou String
o as an assignment symbol
o * as multiplication operator instead of ×. (+: for addition, -: for subtraction, /: for division, there is no
symbol equivalent to the power mathematical operation).

2.1.9. Manual execution of an algorithm


The manual process of an algorithm allows us to follow the execution result by hand, instruction by instruction.
This will give an idea of the execution on a machine of the same algorithm after having translated it into a
program.
To be able to execute an algorithm by hand, we draw up a table, with a number of columns equal to the number
of variables + 1 (the last column is reserved to represent what is displayed on the screen), and at this stage of
course, a number of lines equal to the number of instructions + 1 (one instruction per line + the line containing
the variable names). Subsequently in this course (especially in the loops section), we will be able to correspond
several instructions to a single line.
The order in which the instructions are executed is important, they are executed instruction by instruction from
start to finish.

6
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

Example
Algorithm Algorithm execution with value 2.5:
Algo Aire
Var R A Screen
R, A : Real
2.5
Begin
Read(R) 19.625
A 3.14 * R * R
Write(A) 19.625
End

2.1.10. Comprehension questions


1. The algorithm is: 2. 3. In C language, semicolons are:
A. code. A. Algorithmics were created A. absent.
B. pseudo code. in the service of programming. B. optional.
C. a mix between code and B. programming was created in C. required.
pseudo code. the service of algorithms.
D. simple text. C. algorithmics and
programming are independent.
4. Each line of the body of the 5. The first line of the algorithm is 6. After the first line of the
algorithm is called: : called: algorithm comes the block:
A. Order. A. header. A. Definition.
B. Operation. B. introduction. B. Declaration.
C. Instruction. C. beginning. C. Typing.
D. line. D. Header.
7. In our algorithmic syntactic 8. The algorithm is supposed to be: 9. The instruction that gives
conventions, semicolons are: A. directly executable on control to the user to enter a value
A. absent. machine. is:
B. optional. B. not directly executable A. Show.
C. obligatory. on machine. B. Write.
C. executable only after C. Read.
transformation into code. D. Enter.
10. We write the assignment 11. Write instruction allows: 12. The order of instructions in an
statement as follows: A. enter data. algorithm is:
A. = B. to display results on A. important
B. == screen B. is not important
C. C. to display results printed
D. receives on paper.
D. to print results on
screen.

7
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

2.1.11 Exercises
Exercise 01: The algorithm of the 1st box is syntactically correct. Identify the syntactical errors in each of the
following scripts (2, 3, 4 and 5).
1 2 3 4 5
Algo Exo8 Algo Exo8 Algo Exo8 Algo Exo8 Algo Exo8
Var Var Var Var Var
a : Integer a : integer a : Integer b : Real af : Integer
b : Real b : Real b : Real a : Integer b1: Real
Begin Begin Begin Begin Begin
Read(a) Rid(a) Read(a) Read(a) Read(af)
b a/2 * 5 b a/2* 5 b a/2 * 5 b= x 5 b1 af/2 * 5
Write(b) Show(b) Write(b) Write(b1)
End Write b End End End
End
Exercise 02: What is the final result of running the following algorithm:
Algo Exo1_4
Var
A, B : Integer
C : Real
Begin
Read (A)
B 0
A A*A
B A+B
C A+B/A+5
Write (C)
End
For A = 2 , C =
Exercise 03:
a- Run the following algorithm for values PI=150 and R=30.
Algo Exo3
Var
IP, R, PP : Real
Begin
Write("Please give the initial price and discount")
Read(IP,R)
PP IP –IP * R /100
Write("The price to pay is ", PP)
End
b- What is displayed on the screen for each of the following case ?
PP 105 PP 105 PP 105
Write("The price to pay is ", PP) Write("The price to pay is PP") Write("The price to pay is " PP)
IP 150 IP 150
PP 105 PP 105
Write("The initial price is IP and The price to pay is PP") Write("The initial price is ", IP, " and The price to pay is ", PP)

IP 150 IP 150
PP 105 PP 105
Write("The initial price is IP and The price to pay is ", PP) Write("The initial price is ", " IP and The price to pay is ", PP)

8
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

2.2. Equivalent algorithms


Consider the following two algorithms which allow the area of a circle to be calculated from its radius entered
by the user.
Algo Area1 Algo Area2
Var Var
R, A : Real R, A, Pi : Real
Begin Begin
Read (R) Read (R)
A 3.14 * R * R Pi 3.14
Write (A) A Pi * R * R
End Write (A)
End
Both algorithms are correct, and if executed (after translating them into programs), the user will find that they
do exactly the same thing: ask him to enter the value of the radius, and display the area of the corresponding
circle. These two algorithms are said to be equivalent.
- Two algorithms are equivalent when they have the same behavior from the user's point of view with
regard to the corresponding inputs and outputs.
- Two algorithms are equivalent when they always give the same results regarding the same input sets.

2.2.1. Optimal (best) algorithm


The question that arises directly from the notion of equivalence of algorithms is the following:
- Between two (or more) equivalent algorithms, which is the best?
Dans notre niveau de 1er semestre de 1ère année, on demande généralement aux étudiants d’écrire des
algorithmes corrects et non pas nécessairement optimaux.
To answer this question, there are several criteria. At this 1st year level, we are going to focus on two points:
execution time and memory space consumption.
For the first point, reducing the execution time amounts to reducing the number of instructions and/or
operations. For the second point, reducing memory space means reducing the number of variables used.
In the previous example, the Area1 algorithm is better than the Area2 algorithm, since it has a smaller number
of instructions and variables.
It is not always possible to have an algorithm that is optimal in terms of execution time and memory space at
the same time. In this case, we try to find a compromise between the two criteria.
In 1st semester of 1st year level, students are generally asked to write correct algorithms and not necessarily
optimal ones.

2.2.2. Indicative and explanatory messages


To prevent the user from being lost and not knowing what to enter when they simply see the cursor flashing, we
generally add indicative and explanatory messages (labels) to make the execution more understandable by the
user. For example, we can modify the Area1 algorithm as follows:
Algo Area1
Var
R, A : Real
Bagin
Write ("Please enter the radius of a circle in cm ")
Read(R)
A 3.14 * R * R
Write("The area of this circle is: ", A, " Cm2")
End
Indicative and explanatory messages are not taken into account in the search for algorithm’s optimality.
9
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

2.2.3. Questions de compréhension


1. Two algorithms are equivalent: 2. We judge that one algorithm is better 3. When X= 12, the instruction
When they only have the than another on two points: Write("The average is:", X)
same inputs. A. readability and comfort. displays:
B. when they always have the B. speed and comfort of the A. The average is: 12
same results regarding the programmer. B. The average is:12
same input sets. C. execution time and memory C. The average is:X
C. when they have the same space.
set of instructions.
4. When X= 12, the instruction
Write("the average is:", X, "out of 20"),
displays:
A. the average is: Xout of 20
B. the average is: 12 out of 20
C. the average is:12out of 20
2.2.4. Exercises
Exercise 01 :
Consider the following treatment: A. With 4 instructions and 3 variables; a single
1. Give the user a hand to enter an integer. instruction for each of the steps and a separate
2. Add 5 to this number. variable for each of the first three instructions.
3. Multiply the result by 3. B. With 4 instructions and 2 variables.
4. Show the final result. C. With 4 instructions and 1 variable.
Write six (6) variants of algorithms that carry out the D. With 3 instructions and 2 variables.
previous processing and execute (unroll) each time E. With 3 instructions and 1 variable.
with the value 1: F. With 2 instructions and 1 variable.

Exercise 02 :
We want to permute the values of two integer variables A and B.
1- Run the following two algorithms with the values (6, 17):
Algo Exo1_19_A Algo Exo1_19_B
Var Var
A, B : Integer A, B : Integer
Begin Begin
Read(A, B) Read(A, B)
A B B A
B A A B
Write(A, " ", B) Write(A, " ", B)
End End

2- Rewrite the algorithm to allow the two variables to be swapped correctly, and verify it by running it with the
same values from question 1.
• Questions 3 and 4 are Additional.
3- Write the algorithm which allows you to permute the values of 3 variables A, B and C, in a circular way as
follows:

A B C
4- Generalize for 4 and 5 variables.

10
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

2.3. Types of variables


A variable is the association of an identifier (a variable name) and a memory slot that can contain data. A
variable can be of type Integer like the example in section 2.1.2, Real like the example in section 2.1.5,
character, or string like the following example:

Algo Welcome
Var
FN, LN : String
Begin
Write ("Please what is your first and last name?")
Read (FN, LN)
Write ("Bonjour ", FN, " ", LN)
End

In this example, we ask the user to give him first and last name and we display a welcome message: Hello first
name last name. If the user enters Salmi for the last name and Karim for the first name, the algorithm will
display: Hello Karim Salmi
The only operation that can be applied to character strings at the moment is concatenation, which is
symbolized with the character +.
The previous algorithm can be rewritten as follows:

Algo Welcome2
Var
FN, LN, FullN : String
Begin
Write("Please what is your last and first name?")
Read(LN, FN)
FullN FN + " " + LN
Write("Hello ", FullN)
End
For the character type, here is an example:
Algo Welcome3
Var
F, L : Char
Initials : String
Begin
Write ("Please give the first letter of your first and last name")
Read (F, L)
Initials F + '.' + L
Write ("Hello ", Initials)
End
In this example: if the user enters F = 'K' and L = 'S', the algorithm displays: Hello K.S
Remarquer qu’on délimite un caractère (comme le point dans cet exemple) par simples cotes et non pas doubles
cotes comme pour les chaînes de caractères.
Note that we delimit a character (like the point in this example) by single quotes and not double quotes as for
character strings.

11
Course: Introduction to algorithms Abdelhamid Mehri – Constantine 2 University
Dr. Mohamed BADECHE Common Core – MI, NTIC Faculty – 1st year (2023-2024)

2.3.1. Exercise
Write an algorithm that asks the user to enter their last name, first name, age and address. And displays the
entered information as follows:

++++++++++++++++++++++++++++++++
Hello Salmi Karim
You are: 18 years old
You live in : Benboulaid City – Constantine
----------------------------------------------------

12

You might also like