Professional Documents
Culture Documents
AlgorithmBasicsLectures Update
AlgorithmBasicsLectures Update
Table of contents
3
Syllabus
4
Syllabus
I-
Syllabus
1. Overview of algorithm
2. Objects and data types
3. Sequencing, operators and base instructions
4. Control structures
5. Arrays
6. Some bases algorithms
7. Procedure and Functions
8. Records and Files
5
Chapter 1:
II-
II
Overview on
algorithms
Introduction
A computer engineer is expected to tackle any given problem in the most efficient
manner. This efficiency can be in terms of memory or time or both. However,
efficiency becomes important only if the solution, proposed by the person, solves
the problem. The steps followed to do so constitute an algorithm. This chapter
introduces the concept of algorithm, discusses the ways of writing an algorithm,
and explores the basics of algorithmic designing. We start with the informal
definition of an algorithm.
Definition : Algorithm
Algorithm refers to the steps to be carried out in order to accomplish a particular
task.
Algorithms are used everywhere, from a coffee machine to a nuclear power plant. A
good algorithm should use the resources such as the CPU usage, time, and memory
judiciously. It should also be unambiguous and understandable. The output
produced by an algorithm lies in a set called range. The input, is taken from a set
‘domain' (input constraints). From the domain only the values satisfying given
constraints can be taken. These constraints are referred to as input constraints.
Input constraints determine the values of xi, i.e., input. The inputs are related to
each other as governed by relation corresponding to the task that is to be
accomplished. This is referred to as explicit constraint.
1. Overview
7
Chapter 1: Overview on algorithms
8
Chapter 1: Overview on algorithms
Definition
An algorithm is a sequence of steps in order to carry out a particular task.
It can have zero or more inputs.
It must have at least one output.
It should be efficient both in terms of memory and time.
It should be finite.
Every statement should be unambiguous.
The meaning of finite is that the algorithm should have countable number of steps.
It may be stated that a program can run infinitely but an algorithm is always finite.
However, Algorithm 1.1, in spite of being simple, is not commonly used. The
flowchart or a pseudocode is more common as compared to ‘English-like algorithms'
9
Chapter 1: Overview on algorithms
10
Chapter 1: Overview on algorithms
11
Chapter 1: Overview on algorithms
12
Chapter 1: Overview on algorithms
13
Chapter 1: Overview on algorithms
A. Algorithmic approach
Definition : Algorithm
An algorithm is an ordered sequence of operations to obtain a definite result in
finite time. The reason for an algorithm is to solve a problem. The greatest
attention must be paid to understanding the problem to be solved, which is the
most critical step in the design of an algorithm. Algorithmics is the science that
studies algorithms. It allows to :
Describe a methodical approach to programming,
Master the complexity,
Ensure easy maintenance,
Lower the costs, ...
Have you ever opened a cookbook?
Have you ever pointed the way to a lost tourist?
Have you ever search an item for someone by phone?
If yes, without knowing it, you have already run an algorithm.
Like what, the algorithm is not a mysterious knowledge reserved for a few rare
initiates touched by the divine grace, but an aptitude shared by the totality of the
humanity.
Once executed correctly, an algorithm leads to a given result. So, if an algorithm is
right, its result will be the desired or expected result. On the other hand, if an
algorithm is false, the result will be if it can be said random.
A good algorithm must be:
Readable: the algorithm must be understandable even by a non-computer
scientist
Always ends: the algorithm must have an end
Accurate and unambiguous: each element of the algorithm should not be
confusing
Concise: An algorithm must not exceed one page. If this is the case, it is
necessary to split the problem into several sub-problems.
Structured: an algorithm must consist of different easily identifiable parts.
Solve the problem.
Let us define below all the elementary operations to be performed between the
moment the alarm rings and the moment when we go out to work.
14
Chapter 1: Overview on algorithms
Simulator
We can see in this example that the order of operations is important. Indeed, it
would be very embarrassing to invert actions 2 and 4 or actions 4 and 5.
Suppose then that this sequence of instructions is described by a person in
possession of an umbrella. Thus, it would be necessary to envisage a structuring of
the continuation of the operations allowing him to take his umbrella or coat only in
the event that it rained. For this, we must have an alternative structure to make a
choice. Likewise, if this person has to respect these same gestures every day until,
for example, they are on holiday, we must have an iterative or repetitive structure
to respect this sequence of actions until the awakening do not ring anymore.
Method : Principe
Before developing an algorithm, it is necessary to:
Understand the nature of the problem and specify the data to be provided
(inputs).
Specify the results you want to obtain (outputs).
Determine the process of transforming data into results.
In algorithmic, each elementary task is described by a simple and understandable
expression (or word).
Given: A, B
Result: X
Process: Determine X in AX + B = 0 according to the different possible cases.
15
Chapter 1: Overview on algorithms
16
Chapter 1: Overview on algorithms
Conclusion
Throughout this lesson, we were talking about introducing the notion of algorithm,
giving the characteristics of an algorithm and giving the algorithm development
process. Life is only algorithmic and thanks to the algorithms, the man finds the
solutions to his problems if the algorithm is well elaborated.
17
OBJECT AND TYPE
III -
III
OF DATA
Object
The universe of objects of a treatment is finished. It is therefore possible to fully
and unambiguously describe an object. The processing of an object concerns the
value of this object. If this value can not be changed, we are talking about constant
otherwise we are talking about variable. An object is perfectly defined if we know
its name (its identifier), its type and its value.
Types
There are two main advantages:
To describe the objects of the same nature and admitting the same
operations, it suffices to have defined the type once and for all and to
indicate for a given type, the list of associated objects; we avoid painful
repetitions.
There is a way to detect a number of errors without running the program
simply by examining object operations and checking that they are legal.
19
OBJECT AND TYPE OF DATA
x NOT(x)
20
OBJECT AND TYPE OF DATA
TRUE FALSE
FALSE TRUE
Table 2 NOT(x)
x y xORy
x y xANDy
Object statement
Constant
To declare a constant, we must specify in the declaration part of the constants its
name and its value. The syntax is as follows:
Const identifier = value;
where value refers to one of the base type values.
The identifier thus defined has the type to which the value belongs. The identifier is
composed of letters or numbers. It must obligatorily start with a letter.
Example:
Const PI = 3.14;
EPSI = 0.000042;
WHITE = '';
Variable
To declare a variable, one must specify in the variable declaration part its name, its
type and possibly its value.
The declaration syntax is as follows:
Var identifier: type; or var identifier = value: type; or type is one of the basic
types and identifier is the name given to the variable.
21
SEQUENCING,
IV-
IV
OPERATORS AND
BASIC
INSTRUCTIONS
Sequencing
To analyze a problem is to look for the different steps necessary to solve it. To do
this, it is divided into sub-problems that will be executed one after the other, that is
to say, sequentially. The sub-problem decomposition is made until a series of
atomic elementary processes is obtained. These elementary processes are called
instructions.
The decomposition of a problem P into sub-problems P1, P2, P3 is done by
separating the sub-treatments by the character "; ". The start and end keywords
are used to delimit the processing.
A description of an algorithm with sequential processing can be given by the
following example:
1 Algorithm example;
2 Declaration of objects;
3 begin
4 If (condition) then
5 begin
6 P1;
7 P2;
8 P3;
9 end
10 endif
11 end
Basic instruction
a) Display
The writing order will be given by the instruction write. The syntax is: write
(exp1, exp2, exp3, ..., expn) where expi can represent an expression, a
character, a string, ...
The different values of the expi expressions are displayed one after the other in the
order indicated. Note that these sequences are separated by commas (,) and not by
semicolons (;).
Example:
write ('The square of 4 is', 4 * 4); will produce: The square of 4 is 16.
23
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS
b) comment
to improve the readability of an algorithm, we can use comments:
A comment is a sequence of characters framed by co and fco.
1 Algorithm compute_disk_area;
2 Const PI = 3.14; co value of PI fco
3 Var radius = 1.24; co fco radius value
4 begin
5 Co this algorithm calculates and displays the area of a disc of
radius 1.24 fco
6 Write ('The area of the radius disc', radius, 'is', PI * radius *
radius);
7 End
This algorithm displays: The area of the radius disc 1.24 is 3.8936.
c) variables
When a T-treatment is decomposed into sub-treatments T1, T2, ...; it is common
for the Ti subprocessing to use, for example, the intermediate result produced by a
Tj. These intermediate results r1, r2, ... that lead to a result r do not often need to
be preserved. Rather than designate them all by different constraints, we choose to
designate them by the successive values of the same object called variable. Thus, a
variable appears as a box whose contents can be modified during the execution of
the algorithm by the assignment instruction. The contents of this box is called the
value of the variable. A variable must be designated by a name or an identifier in
order to be identified.
The syntax is as follows:
Var identifier: type;
Or type designates one of the basic types;
Identifier is the name given to the variable
Note 1: We can factor the declaration of several variables of the same type by
separating them by commas
Note 2: The choice of the identifier must be judicious and evoke as much as
possible the role played by this variable. This choice is not always sufficient, we can
specify the role of the variable by a comment.
Example var x, y: real; co coordinates of a dot fco
d) Allocation or assignment
The assignment statement has the effect of modifying the value contained in a
variable. The syntax is as follows:
Identifier: = expression; or identifier<-expression;
where the symbols ": =" or "<-" represents the assignment symbol
Note: The expression must be of the same type as the identifier.
Example var x: integer;
In an algorithm, we can have the instruction
x: = 10; the variable x then contains 10 fco
x: = x + 40; co the variable x then contains 50 fco
e) Reading
The read instruction is used to modify the contents of a variable, the syntax is as
follows:
read (identifier);
The read instruction causes the interrupt of the machine waiting for a value to be
24
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS
supplied to it. The user then strikes a keyboard value that is assigned to the
variable designated by identifier. The value must be of the same type as the
receiving variable.
As for the display, we can factorize the reading instructions.
Thus, the writing is as follows: read (ident1, ident2, ..., identn); which
expresses "to read (ident1); read (ident2); ... read (identn);"
Note
We note in this example that to calculate the volume we use the result of the
previous calculation (that of the surface) to minimize the number of operations.
1 Algorithm computation;
2 x, y, z: integer;
3 begin
4 x:=5;
5 y:=10;
6 z:=2*x-y;
25
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS
7 z:=y-6;
8 y:=x+z+6;
9 x:=6*y;
10 write (x);
11 y:=y-1;
12 write (y,z);
13 end
14
26
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS
year into a date that expresses the number of the day in the month. For example
32/2007 corresponds to 01/02/2007
Exercise 18: Number between two days
Propose an algorithm to calculate the number of days between two given dates in
the form dd / mm / yyyy. It is assumed that both dates belong to the same year.
Exercise 19: Date of the following day
Propose an algorithm that reads a date in the form dd / mm / yyyy and determines
the date of the next day.
Exercise 20: System of equations
Write an algorithm that solves a linear system of two equations with two unknowns
parameters.
Exercise 21: Magic square
A magic square is a matrix of order n whose elements are all integers between 1
and n2 such that the sum of the elements of each column and the sum of the
elements of each diagonal line are equal. Propose an algorithm that builds a magic
square of order n.
Exercise 22:Verification of a permutation
Write an algorithm that reads an integer n then a permutation of n elements and
verifies that the values entered constitute a permutation of 1, ..., n.
Exercise 23:
Write an algorithm that reads 2 square matrices of order n, posters, calculates their
product and displays.
Exercise 24:Scalar product of two vectors
Let U and V be two vectors of real n and of components u 1, u2, ..., un and v1, v2 ...,
vn respectively. Calculate the U * V scalar product.
27
CONTROL
V-
V
STRUCTURES
A. Conditional structure
29
CONTROL STRUCTURES
Example
Write an algorithm that displays the result in the exam of a student whose grade is
being read in data. It is admitted if its mark is greater than or equal to 10,
postponed if its mark is <8 and admitted orally if its mark is between 8 and 10.
1 Algorithm dysplay_result;
2 var mark:real;
3 begin
4 write("Type the name of the student");
5 read(mark);
6 if(mark>=10)then write("Admitted");
7 else
8 if(mark<8)then write("postponed");
9 else write("Admitted for oral");
10 endif
11 endif
12 end
B. Repetitive structure
Introduction
In many problems, one is required to perform several actions several times.
Example: the calculation of the payroll of employees of a company, the edition of
the transcripts of the students of a faculty, the edition of the invoices of the
customers, ...
If the number of repetitions is large, it is tedious to rewrite the same algorithm n
times, this is impossible in some cases, even in the majority of cases. It is therefore
wrong to be able to express the repetition of an action or an iteration that once
initialized continues until an event occurs: it is the event of stop of the iteration.
Example
A program segment repeatedly asks for entry of a number in the range 1 to 100
until a valid number is entered.
30
CONTROL STRUCTURES
1 REPEAT
2 write(“Enter a number between 1 and 100”);
3 read(number);
4 UNTIL (number < 1 OR number > 100 )
1 Algoritm sport_survey;
2 Var letter: char;
3 athletics,swimming,football, badminton: integer;
4 BEGIN
5 REPEAT
6 write(“Type in the letter chosen or Q to finish”);
7 write(“A: Athletics”);
8 write(“S: Swimming”);
9 write(“F: Football”);
10 write(“B: Badminton”);
11 write(“Enter data”);
12 read(letter);
13 If (letter = ‘A') then athletics = athletics + 1;
14 If (letter = ‘S') then swimming = swimming + 1;
15 If (letter = ‘F') then football = football + 1;
16 If (letter = ‘B') then badminton = badminton + 1;
17 UNTIL (letter = ‘Q')
18 write(“Athletics scored”, athletics, “votes”);
19 write(“Swimming scored”, swimming, “votes”);
20 write(“Football scored”, football, “votes”);
21 write(“Badminton scored”, badminton, “votes”);
22 END
Example
A program segment to print out each character typed at a keyboard until the
character ‘q' is entered.
Write a program that will output the square root of any number input until the
number input is zero.
In some cases, a variable has to be initialized before execution of the loop as shown
in the following example.
31
CONTROL STRUCTURES
1 Algorithm square_root;
2 Var number :real;
3 BEGIN
4 write(“Type in a number or zero to stop”);
5 read(number);
6 WHILE number <> 0
7 Square = number * number
8 write(“The square of the number is”, square);
9 write(“Type in a number or zero to stop”);
10 write(number);
11 ENDWHILE
12 END
Example
1 FOR (n = 1, n <= 4, n + 1)
2 write(“loop”, n);
3 ENDFOR
1 Algorithm average;
2 Var n, count :integer;
3 Sum, number, average :real;
4 BEGIN
5 write(“How many numbers do you want to input”);
6 read(count);
7 Sum = 0;
8 FOR (n = 1, n <= count, n + 1)
9 write(“Input the number from your list”);
10 read(number);
11 Sum= sum + number;
12 ENDFOR
13 Average = sum / count;
32
CONTROL STRUCTURES
Design an algorithm and the corresponding flowchart for finding the sum of n
numbers.
1 Algorithm integer_sum;
2 Var n, sum:integer;
3 Begin
4 sum = 0;
5 write(“Input value n”);
6 read(n);
7 For i from 1 to n do
8 write("Input a value");
9 read(value);
10 sum = sum + value
11 ENDFOR
12 write(sum);
13 End
In this example, we have used I to allow us to count the numbers, which we get for
the addition. We compare I with n to check whether we have exhausted the
numbers or not in order to stop the computation of the sum (or to stop the iteration
structure). In such a case, i is referred to as a counter.
C. Exercises
Exercises
1. Design an algorithm and the corresponding flowchart for finding the sum of
the numbers 2, 4, 6, 8, ..., n
2. Using flowcharts, write an algorithm to read 100 numbers and then display
the sum.
3. Write an algorithm to read two numbers then display the largest.
4. Write an algorithm to read two numbers then display the smallest
5. Write an algorithm to read three numbers then display the largest.
6. Write an algorithm to read 100 numbers then display the largest.
7. Write an algorithm to display the sum of the 100 numbers read in data. The
algorithm will also display their average.
8. Write an algorithm that displays the L character followed by the E character
(LE) in a sentence that ends with the symbol"."
9. Write an algorithm that calculate an were a and n are read from the
33
CONTROL STRUCTURES
keyboard.
10. Write an algorithm which read a value n as input compute Un=Un-1+Un-2
whith U0=U1=1
11. Write an algorithm to determine the greatest common divisor (GCD)of two
numbers read as input
12. Write an algorithm that determines and displays the number of words
contained in a sentence completed by the dot marker ".". To put it simply,
we will consider that the separator character of the words is ' ' (the blank
space) there are no other separators.
13. Let s be a sequence of positive integers ordered in ascending order and
terminated by the -1 marker. Write an algorithm to determine the length L
of the longest sub-sequence extracted from s and having only identical
elements. e.g if the following is s = 11227779-1, L = 3.
14. Write an algorithm that prints the successive terms of the general term
sequence 1/(2 * n). Suppose that n> 0. The printing is made until a term
is less than 0.0001
15. Write an algorithm that calculates the series 1-1/3+1/5-1/7+...+(-1)n/
(2*n+1) with a precision whose value will be read in data.
16. Write an algorithm that calculates an approximate value of sin (x), with x in
rad. The algorithm will use the x-x3/3!+x5/5!-x7/7!+...+(-1)nx2n+1/(2n!)
development for evaluating sin (x)
34
Section
VI-
VI
35