You are on page 1of 41

Algorithm basics

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

What is computer science?


Computer science is the study of computation investigating problems that can be
solved computationally programming languages used to describe computations
machines that carry out computations theoretical limits of computation (what is or
is not computable) computational solutions to problems in math, science, medicine,
business, education, journalism, ...
Computers play a key role but computer science is not “about computers”

What is information processing?


An information is considered as element than can be represent using symbols to
store, process and communicate. Examples of information processing follows:
 At a school campus: register ant control attendances, publish school results,

7
Chapter 1: Overview on algorithms

edit and print report card.


 In a company: payroll, billing, stock management, accounting
 In mathematics: solving an equation, compute integrals, demonstrate a
theorem, solve a differential equation,...
 In army: recognize a tank on an image taken by satellite, act on enemy
ground, guide drones for an attack,...
The list of domains is not exhaustive. Computer science appears as cross discipline.
Computer science borrows mathematics logic, uses social science as application
domain and electronics as hardware technology.

The above image illustrate the


information processing. The difficulty
of information information processing
states how to operate on data to reach final results. Computer science automates
the process, i.e assign the information processing to machines.

What are the steps of information processing?

WAYS OF WRITING AN ALGORITHM


There are various ways of writing an algorithm. In this section, three ways have
been explained and exemplified taking requisite examples.

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.

Fundamental : 1.5.1 English-Like Algorithm


An algorithm can be written in many ways. It can be written in simple English but
this methodology also has some demerits. Natural languages can be ambiguous and
therefore lack the characteristic of being definite. Since each step of an algorithm
should be clear and should not have more than one meaning, English language-like
algorithms are not considered good for most of the tasks. However, an example of
linear search, in which an element is searched at every position of the array and
the position is printed if an element is found, is given below. In this algorithm, ‘A' is
the array in which elements are stored and ‘item' is the value which is to be
searched. The algorithm assumes that all the elements in ‘A' are distinct. Algorithm
1.1 depicts the above process.

1 Algorithm 1.1 english-like algorithm of linear search


2 Step 1. compare ‘item' with the first element of the array, A.
3 Step 2. If the two are same, then print the position of the element
and exit.
4 Step 3. else repeat the above process with the rest of the elements.
5 Step 4. If the item is not found at any position, then print ‘not
found' and exit.

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'

Fundamental : 1.5.2 Flowchart


Flowcharts pictorially depict a process. They are easy to understand and are
commonly used in the case of simple problems. The process of linear search,
explained in the previous subsection, is depicted in the flowchart illustrated in Fig.
1.1. The conventions of flowcharts are depicted in Table 1.1.

9
Chapter 1: Overview on algorithms

10
Chapter 1: Overview on algorithms

In the flowchart, shown in Fig 1.1, A[ ] is an array containing N elements. The


index of the first element is O which is also the initial value of i. Such depictions,
though easy to comprehend, are used only for simple straightforward problems.
Hence, this book neither recommends nor uses the above two types for writing
algorithms, except for some cases.

Fundamental : 1.5.3 Pseudocode


The pseudocode has an advantage of being easily converted into any programming
language. This way of writing algorithm is most acceptable and most widely used.
In order to be able to write a pseudocode, one must be familiar with the
conventions of writing it.
Table 1.2 shows the pseudocode conventions.

Fundamental : Pseudocode convensions

S. No. Construct Meaning


// Comment Single line comments start with //

11
Chapter 1: Overview on algorithms

"/* Comment Line 1 Multi-line comments occur


Comment Line 2 between /* and */
...
...
Comment Line n
*/"
"{ "Blocks are represented using
statements { and }. Blocks can be
}" used to represent compound
statements (collection
of simple statements) or the
procedures."
; Statements are delimited by ;
<variable> = <Expression> This is an assignment statement.
The statement indicates that the
result of evaluation of the
expression will be stored in the
variable.
a > b "a and b are expressions, and > is
a relational operator ‘greater
than'. The Boolean expression a >
b
returns true if a is greater than
b, else returns false."
a < b a and b are expressions, and < is
a relational operator ‘less than'.
The Boolean expression a < b
returns true if a is less than b,
else returns false.
a <= b a and b are expressions, and <= is
a relational operator ‘less than
or equal to'. The Boolean
expression a <= b returns true if
a is less than or equal to b, else
returns false.
a >= b "a and b are expressions, and >=
is a relational
operator ‘greater than or equal
to'. The Boolean expression a >= b
returns true if a is greater than
or equal to b, else returns
false."
a != b a and b are expressions, and != is
a relational operator ‘not equal
to'. The Boolean expression a != b
returns true if a is not equal to
b, else returns false.
a == b "a and b are expressions, and ==
is a relational
operator ‘equal to'. The Boolean
expression a == b returns true if

12
Chapter 1: Overview on algorithms

a is equal to b, else returns


false."
a AND b a and b are expressions, and AND
is a logical operator. The Boolean
expression a AND b returns true if
both the conditions are true, else
it returns false
a OR B a and b are expressions, and OR is
a logical operator. The Boolean
expression a OR b returns true if
any of the condition is true, else
it returns false.
NOT a a is an expression, and NOT is a
logical operator. The Boolean
expression ‘NOT a' returns true if
the result of a evaluates to
False, else returns False.
if<condition>then<statement> The statement indicates the
conditional operator if.
"if<condition>then<statement1> The statement is an enhancement of
else<statement2>" the above if statement. It can
also handle the case where in the
condition is not satisfied.
"Case The statement is a depiction of
{ switch case used in C or C++.
:<condition 1>: <statement 1>
....
...
:<condition n>: <statement n>
:default: <statement n+1>
}"
"while<condition>do The statement depicts a while loop
{
statements
}"
"repeat The statement depicts a do–while
statements loop
until<condition>"
"for variable = value1 to value2 The statement depicts a for loop
{
statements
}"
Read Input instruction
Print Output instruction
Algorithm<name> (<parameter list>) The name of the algorithm is
<name> and the arguments are
stored in the <parameter list>

13
Chapter 1: Overview on algorithms

Table 1 Pseudocode convensions

Algorithm 1.2 linear search

1 Algorithm Linear_Search(A, n, item)


2 {
3 for i = 1 to n step 1 do
4 {
5 if(A[i] == item)
6 {
7 print i;
8 exit();
9 }
10 }
11 print “Not Found”
12 }

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

1. The alarm clock rings


2. I wake up
3. I get up
4. I'm showering
5. I get dressed
6. I prepare breakfast
7. Have breakfast
8. If it rains, I put on the coat or I take the umbrella
9. I open the door
10. I'm going out
11. I close the door

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.

Method : Method of solving an algorithm


Generally speaking, an analysis of a problem in order to solve it can be reduced to
a sequence of interrogations which follow one another:
 What is the result to obtain? (What do we want)
 What operations can be developed in order to solve this result? (How is the
result obtained?)
 What data are needed to complete these operations? (What is needed?)
Whatever type of problem we will have to deal with, the analysis will consist of:
 Define the problem precisely to identify the result (s) (outputs) to obtain.
 Identify treatments for obtaining the result within the stated problem
 Identify the information (inputs) necessary to carry out the treatments
envisaged
 Roll out the algorithm step by step through a set of tests to see if it
produces the requested result.

15
Chapter 1: Overview on algorithms

B. General structure of an algorithm

Algorithm Definition Language (LDA) and keywords


An LDA is a set of keywords and structures that provide a complete and clear
description of all the operations to be performed on data to obtain results; we will
not hesitate to enrich a LDA many comments. The advantage of such a language is
that it can be easily transcribed in a programming language.
In an LDA, some words are reserved for a well defined use, they are called
keywords. These are the words that language uses for its operation.
NB: A keyword can not be declared as an identifier. It can not be used as a variable
either.
A few key words: in our LDA, keywords will always start with a capital letter and
will be underlined. The ones that allow us to define the structure are:
 Algorithm: allows you to define or give the name of the algorithm
 Start: marks the beginning of the algorithm
 End: marks the end of the algorithm
 Variables: this is a part of the algorithm that makes it possible to declare
variables; a variable is an object whose contents may change during the
execution of an algorithm.
 Constants: it is the part of the algorithm that makes it possible to declare
constants. A constant is an object whose content remains invariant when
running an algorithm.
 Real, Characters, Integers, String and Boolean are keywords that
define types (we will come back to this in the next chapter)
 If, endif, while, endwhile, for, endFor, Repeat, Up, ...: keywords to
define the iterative, conditional structures.
Comments are used to allow an easy interpretation of the algorithm. Their use is
highly recommended. As a result, any text placed between the symbols / * * / will
be considered as comment.

General structure of an algorithm


1. Header Algorithm name_of_the_algorithm
2. Statement of constants and variables
- Constants
list of constants
- Variables
list of variables
3. Statement of procedures and functions
- functions
list of functions
- procedures
list of procedures
4. Body of the algorithm
begin
- instruction1;
- instruction2;
- instruction3;
...
- instructionn;
end
The header: this part simply allows to give a name to our algorithm. In general,
we need to ring names that speak to our algorithms, this to give the reader an idea
of what the algorithm will do.

16
Chapter 1: Overview on algorithms

Statements: This is an exhaustive list of objects, quantities used and manipulated


in the body of the algorithm. This list is placed at the beginning of the algorithm.
The body: in this part of the algorithm are placed the tasks (instructions,
operations ...) to be executed by our algorithm.
All keywords are underlined and begin with a capital letter.

Extra : Worked exercise


Statement
Your grandfather owns a rectangular piece of land in the village. He would like to
know the area occupied by his land.
Work to do :Design an algorithm that allows your grandfather to solve his
problem.
1. Analysis
- What is the desired result? (Output): we want to get the value of the
area (area) occupied by the grandfather's parcel of land.
- How is the result obtained? (Treatment): the land is rectangular in
shape. A rectangle is a geometric figure of 4 sides and consists of a
length (L) and a width (l). To obtain the surface, it is necessary to know
the formula that is to say Surface = Length * width and to do the
calculation of the product by the machine.
- What information is needed? (Inputs): in the formula above, we will need
to know the length and width of the land.
2. Structure of the solution: the solution of the statement implies the
following structuring:
- Give the length (L)
- Give the width (l)
- Calculate the area (S) by performing: S = L * l
- Display the surface (S).
3. Writing the algorithm: To be done by the student

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

Example : Let's define the following types


 Solid: material with a clean form. As an example of operator on a solid, one
can have melt.
 Liquid: material tending to flow. As operator, we have "boil", "drink".
We can define the following sequence:
Subject:
 SOLID: rubber, butter
 LIQUID: water, wine
Action:
 Melt the rubber, Melt the butter
 Drinking wine, Drinking water
 Melt wine???
The above is an algorithm, without performing the actions described in this
algorithm, we notice that the operation melt the wine is wrong because the wine is
a liquid type object and the operation melt the wine is not associated to this guy.

Basic types and associated operations.


There are five basic types that are: integer, real, character, string, boolean
The integer type:
The values associated with this type are integers. Example 10, 12, -3, ...
As operation, we have the usual operations namely: the addition, the subtraction,
the multiplication, the comparison, certain particular operations called functions.
Example: 2+ (4/5); abs (-20); sin (30).
The real type
These are real numbers. The point (.) Is used to separate the integer part of the
decimal part.
Example: 10.1, 11.55, 0.6, 2.0
The operations are the same as for integers.
The character type
It contains all the usual characters. Letters, numbers, and so-called special
characters (dot, comma, operators [,], +, *, -, /, <,>, &, $, {,}, (,), ...
Notation: we surround the character of apostrophes. Example: 'A'; '1'; '0'
As an operator, we have the comparison operators.
string type
A string must be at least two characters in order not to be confused with a
character object. The characters of a string are of character type.
Notation: we surround the chains of quotation marks.
Example: 'hello', '2000'
If the character string contains the apostrophe, it will be doubled.
Example: 'I lost'
As an operator, we have the comparison operators.
Boolean type
There are two possible values: true and false.
As an operator, we have the logical operators no, and, or.
The following table shows the manipulation of logical operators:

x NOT(x)

20
OBJECT AND TYPE OF DATA

TRUE FALSE

FALSE TRUE
Table 2 NOT(x)

x y xORy

TRUE TRUE TRUE

TRUE FALSE TRUE

FALSE TRUE TRUE

FALSE FALSE FALSE


Table 3 xORy

x y xANDy

TRUE TRUE TRUE

TRUE FALSE FALSE

FALSE TRUE FALSE

FALSE TRUE FALSE


Table 4 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

In an algorithm, the symbols "(,.;)" Serve as syntactic delimiters.

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.

Example : write an algorithm that displays the area of a radius disc


1.24

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);"

Example : Write an algorithm that calculates the surface and


volume of a sphere with the radius of the sphere read from the
keyboard.
Algorithm area_vol_spere;
Const PI = 3.14159;
Var R, S, V;
begin
write ('Enter the radius value');
read (R);
S: = 4 * PI * R * R;
V: = S * R / 3;
write ('The surface of the sphere:', S);
write ('The volume of the sphere is:', V);
end

25
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS

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.

Tutorial sheet number 1: introduction to algorithmic


Exercise 1:
Write an algorithm that reads 2 numbers and determines the largest and smallest
Exercise 2: Write an algorithm that reads two integers and displays the quotient
and the rest of the Euclidean division of these two numbers.
Exercise 3:
Write an algorithm that requires the input of any letter of the alphabet. If the letter
entered corresponds to the initial of the day of the week, there is the following
display:
"The letter L corresponds to Monday" if the letter entered is L for example.
"The letter M corresponds to Tuesday or Wednesday" if the letter entered is M for
example.
Otherwise show
"The letter A does not correspond to any day of the week" if it is the case of the
letter A.
Exercise 4: Manual Execution
We consider the following algorithm

1 Algorithm computation;
2 x, y, z: integer;
3 begin
4 x:=5;
5 y:=10;
6 z:=2*x-y;
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

a) perform the manual execution of this algorithm;


b) deduce the values of x, y, and z displayed.
Exercise 5:
Write an algorithm to swap 2 integer objects using an intermediate variable.
Exercise 6:
Write an algorithm that asks you to enter a word from the keyboard, and then
displays the word entered, its first and last letter, and its length.
Exercise 7:
Write an algorithm which reads 10 integer numbers, calculate their sum and
displays the result.
Exercise 8:
Write an algorithm that reads 12 real numbers and calculates the mean, variance,
standard deviation and then displays them.
Exercise 9:
Write an algorithm that reads a positive integer and calculates the factorial of that
number. The algorithm must accept only positive or zero numbers and ignore all

26
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS

negative numbers.
Exercise 10:
Write an algorithm asking to enter a word of any length and determining whether
the word is a palindrome or not. (e.g. redivider, deified, civic, radar, level, rotor,
kayak, reviver, racecar, redder, madam, and refer)
Exercise 11:
Write an algorithm that calculates the sum and the average of the n first natural
integers, then displays the results.
Exercise 12:
Write an algorithm which allows to reads 2 positives integers and calculates their
product using the following principle.
AxB=A+A+A+...+A, (B times).
Exercise 13:
Write an algorithm that reads an integer n and determines whether it is a prime
number or not. Principle: if any number less than n and different from 1 is not
divisor of n, then n is prime.
Exercise 14:
Write the algorithm that asks to enter a square matrix of order n, displays it,
calculates its trace and displays it. The algorithm then searches for the smallest
element of the matrix, the poster and its various coordinates.
Exercise 15:
Write an algorithm that reads an integer and displays its equivalent in binary
Exercise 16:
Write an algorithm that reads an integer n, calculates the elements of the pascal
triangle of depth n and finally displays the triangle thus obtained.
Exercise 17: Date conversion
Propose an algorithm that converts a given date as the number of the day in the
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

27
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS

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.

28
CONTROL
V-

V
STRUCTURES

A. Conditional structure

Consider the followings sentences:


 If it's rains, i do not go out of the house.
 if the weather is nice, I would go for a walk otherwise i stay at home.
These two examples among thousands of others show that our actions are often
conditioned by the realization or not of certain events. Thus, in the description of
the algorithm, we are often forced to make choices between different treatments
according to the result of certain tests or the answer to certain questions. The
conditional structure is done with the help of the instruction if...endif.
Suppose that there is only one condition c to test for performing T1 processing.
This treatment can be done if the condition c is true, and if it is not true, no
treatment can be done. The syntax is as follows:

Syntax : Fist form:


if (c) then T1 endif
Condition c denotes a Boolean expression whose value is true or false. T1 denotes
a sequence of instructions. The flow diagrams are as follows:

If the condition is true, then T1 is


performed and then passed in
sequence. If the condition is false, go
directly to the statement following the
conditional.

Syntax : Second form:


if (c) then T1
else T2
endif

29
CONTROL STRUCTURES

If the condition has the value true, T1


is carried out and then the sequence is
passed in sequence, that is to say to
the instruction following the condition.
If the condition is false, then T2 is
executed and then the sequence is
passed. The flow diagram is as follows:

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.

The repeat loop

Syntax : The syntax is


REPEAT
 A statement or block of statements
UNTIL a true condition

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 )

Example : SPORT SURVEY


A survey has been carried out to discover the most popular sport. The results will
be typed into the computer for analysis. Write a program to accomplish this.

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

The WHILE loop


The second type of iteration we will look at is the while iteration. This type of
conditional loop tests for terminating condition at the beginning of the loop. In this
case no action is performed at all if the first test causes the terminating condition to
evaluate as false.

Syntax : The syntax is


WHILE (a condition is true)
 A statement or block of statements
ENDWHILE

Example
A program segment to print out each character typed at a keyboard until the
character ‘q' is entered.

1 WHILE (letter <> ‘q')


2 read(letter);
3 write(“The character you typed is”, letter);
4 ENDWHILE

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

The FOR Loop


The third type of iteration, which we shall use when the number of iterations is
known in advance, is a for loop. This, in its simplest form, uses an initialization of
the variable as a starting point, a stop condition depending on the value of the
variable. The variable is incremented on each iteration until it reaches the required
value.

Syntax : The pseudo-code syntax will be:


FOR (starting state, stopping condition, increment)
 Statements
ENDFOR

Example

1 FOR (n = 1, n <= 4, n + 1)
2 write(“loop”, n);
3 ENDFOR

The fragment of code will produce the output


Loop 1
Loop 2
Loop 3
Loop 4
In the example, n is usually referred as the loop variable, or counting variable, or
index of the loop. The loop variable can be used in any statement of the loop. The
variable should not be assigned a new value within the loop, which may change the
behavior of the loop.
Write a program to calculate the sum and average of a series of numbers.
The pseudo-code solution is:

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

14 write(“The sum of the numbers is “, sum);


15 write(“Average of the numbers is “, average);
16 END

Flowcharts have been used in this


section to illustrate the nature of the
three control structures. These three
are the basic control structures out of
which all programs are built. Beyond
this, flowcharts serve the programmer
in two distinct ways: as problem
solving tools and as tools for
documenting a program.

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
Array
VI-

VI

Introduction
When a program manipulates many variables that contain “similar” forms of data,
organizational problems quickly arise. Here is an example: In an ice-skaking
competition, each skater's performance is judged by six judges, who assign
fractional scores. The six scores must be collected and manipulated in various
ways, e.g., printed from highest to lowest, averaged, multiplied by weighting
factors, and so on. Say that the six scores are saved in these variables,
 An array is the most basic data structure to visualise
 Most, if not all, computer languages provide it as a builtin
 Definition An array is a collection of elements stored in contiguous memory
locations providing random access to its elements
- The elements are ordered according to an index set, which is a set of
integers
 Random access – accessing any element takes the same time
 Indexing could be either 0-based or 1-based

Applications of arrays
 Despite its simplicity, an Array has wide range of applications
 Best data structure for in memory storage of infrequently changing data
 Many sorting applications use arrays explicitly or as auxiliary data structures
 For implementing other and more complicated data structures
 ... such as Stack, Queue, List, and Search Tree

A. One dimensional Array

1. Definition of array type

Syntax : Definition of array type


The syntax is :
type identifier = array[inf ... sup] of T;
where:
 identifier is the name of the new created type.
 array[inf ... sup] of T is the constructor which enable to define the type
array
 inf and sup are constant identifiers which represent the left and the right
boundary of the array with . These values define the index

35
Array

variation interval.

Example : Definition of array


. is a new type representing
new integer type.
. is a new type representing new
string type.

a) Declaration of arrays object


Syntax
The syntax of declaration is the following:
var : ;
where
 is an array type define in a type declarative part,
 is the name of the variable of type .

Example : Array object declaration


var : ;
is the name of the variable of type

Note : Observation
It is also possible to use the following syntax to declare an array.
var : array of T;
where
 is the name of the variable declare as array type.
inf and sup are constant identifiers which represent the left and the right
boundary of the array with .

i Using an array element


Using an array element
It most be able to select an array element, this is done with the help of the
addressing function named indexation, the located variable is then called
indexed variable, the syntax is the following:
identifier[index];
where:
identifier is the name used during the array declaration.
index is an arithmetic expression with an integer result and with a value falling in
the interval defined by the array boundaries i.e .
1 Exemple

Example
Write an algorithm which allow to read 100 integers, then displays the list of those
integers in the reverse reading order.

1 Algorithm ReverseIntegerList;
2 type intvect:array[1 ..100]of integer;
3 var Arr:intvect;
4 i:integer;

36
Array

5 Begin
6 write("Type in a list of 100 integer");
7 i:=1;
8 Repeat
9 write("Type in the integer number", i);
10 read(Arr[i]);
11 i++;
12 Until(i==101)
13 write(" The reverse array is:");
14 i:=100;
15 while(i>0)do
16 write(Arr[i]);
17 i:=i-1;
18 endwhile
19
20 End

Example : Algorithm: Number of 'a' in a string


Write an algorithm that allow to read a string and return the number of characters
'a' in that string. The maximum length of the string is 100. The '.' is the end of the
string.

1 Algorithm number_of_a;
2 const N:=100;
3 type charvect: array[1 ... N]of char;
4 var A: charvect;
5 count, i :integer;
6 Begin
7 write("Type in a string");
8 i:=1;
9 read(A[i]);
10 while((A[i]<>0)&&(i<=100)) do
11 i+=1;
12 read(A[i]);
13 endwhile
14 if(A[i]=='.')then
15 begin
16 count:=0;
17 j:=1;
18 while(A[j<>0]) do
19 if(A[j]=='a') then count++;
20 endif
21 j+=1;
22 endwhile
23 write("The number of a is:", count);
24 end
25 else write("Typping error");
26 endif
27 End

B. Multidimensional array

We generalize the definition of one dimensional array to two dimensions, tree


dimension, ...

Two dimensional array


The syntax is the following:
type array of T;
 inf1 and sup1 are the line index variation interval.

37
Array

 inf2 and sup2 are the column index variation interval.


Note:

Example
type = array of integer;
var : ;
To have access to an element of the array, we need to know the line and column
indexes of which that element belongs.

Note
represent the element at the position , i.e st the line and column of
the array .

1 2 3 4 5 6 7 8 9

6
Table 5 Illustration of a two dimensional array

Example : Matrix sum


Write and algorithm that allow to:
 Read two matrix of size NxN
 Sum them
 Displays the result

n dimensional array
We can generalize the definition of the one dimensional array to n dimension
following the syntax below:
type of T;
Note:

C. Tutorial set 3

Exercise 1: sum of two vectors


Write an algorithm that allows to read two vector of size N, calculate their sum and
displays the result

Exercise 2: coefficient vector multiplication


Write an algorithm which realizes the scalar product of a vector (of real) and an
integer.

38
Array

Exercise 3: vectors product


Write an algorithm which realize the product of two vectors read in data.

Exercise 4: Matrix multiplication


Write and algorithm that allow to:
 Read two matrix of size NxN
 Multiply them
 Displays the result

Exercise 5: Check
Write an algorithm which displays TRUE if a number nb is equal to the sum of two
consecutive elements of an array A and false otherwise. The number nb and the
array A are read in data.

Exercise 6:
Given two dimensional array(NxN).
write an algorithm that recognize if the array is magic or not.
An array is magic if the sum of the diagonal of N lines and N column are all equals.

39
Searching and
VII-

VII
Sorting

A. Searching

In computer science, we generally have to manipulate a set of data with common


characteristics. One of the most common operations is searching in these sets

a) Some practical examples


A cellphone directory is intended to provide the number of a subscriber given his
name and possibly additional features such as first name or address.
Another quite different example is that of a dictionary where we search the
definition of words by first doing a search of the my to define.

b) sequential search.
The most naive way is to compare the element sought x successively to all the
elements of the list L according to the following sequential diagram:
 The indexes of L are between 1 and the length of the list L
 To compare x and the ith element of the list L, one will be interested at first
in the search for any solution, one stops the progression in the list as soon
as one finds an element equal to x.
In the case where the list is represented by an array A, A [i] designates the i th
element of the list and the following algorithm will tell us if the element x is in the
Array A.

Syntax : Sequential or Linear search

1 Algorithm sequentialSearch;
2 CONST N=100;
3 VAR A: array[1...N] of element;
4 x: element;
5 i: integer;
6 BEGIN
7 write("Type in the array''s elements");
8 for i from 1 to N do
9 write("Type in the",i,"th element");
10 read(A[i]);
11 endfor
12 write("Type in the element to search");
13 read(x);
14 i:=1;
15 while((i<=N)&&(A[i]!=x))do
16 i++;

41
Searching and Sorting

17 endwhile
18 if(i==N+1) then write("Element not found");
19 else write("Element found at position",i);
20 endif
21 END

In this algorithm, the condition of the while loop is double, after each iteration, a
test of the the end of the end of the list is done ( ), equally, the comparison
between x and the element at position is done.

Syntax : Another method


Another method is to use a sentinel i.e. to add an additional element containing the
value at the position in such a way that the output of the loop
always return the element . Then, at the end of the loop, if the position of the
element is N+1, we conclude that the element is not in the initial list, the algorithm
follows:

1 Algorithm sequentialSearch;
2 CONST N=100;
3 CONST M=101;
4 VAR A: array[1...M] of element;
5 x: element;
6 i: integer;
7 BEGIN
8 write("Type in the array''s elements");
9 for i from 1 to N do
10 write("Type in the",i,"th element");
11 read(A[i]);
12 endfor
13 write("Type in the element to search");
14 read(x);
15 i:=1;
16 A[M]='x';
17 while(A[i]!=x)do // a single condition
18 i++;
19 endwhile
20 if(i==M) then write("Element not found");
21 else write("Element found at position",i);
22 endif
23 END

c) Search in a sorted list: Binary search


Suppose now that there is a total order on the items and that the list is sorted in
order. To look for an element , we can of course browse the list
sequentially until we find either or an element greater than , in which case is
not in the list since the elements are arranged in order. Here, the search
is still sequential and it takes very little account of the fact that elements of the
list are arranged in ascending order. Another algorithm taking this into account is
called search, the principle of the search by dichotomy of the element x in
the sorted list L is as follows:
Compare x with the middle element in the list .
• If x = L [M], a solution has been found and the search stops.
• If x> L [M], it is possible that x is before L [M] in the list L and it remains only to
treat the right half of the list L.
• If x <L [M], x can only be in the left half of the L list.
This continues the search by halving the number of items in the remaining list to be
processed after each comparison, and if the list does not contain x, the search ends
with a failure.

42
Searching and Sorting

The algorithm is as follows:

43
Searching and Sorting

Method : Binary search algorithm

1 Algorithm BinarySearch;
2 CONST N=100;
3 VAR A: array[1...N] of element;
4 x: element;
5 i, m, g,d, res: integer;
6 BEGIN
7 write("Type ine the array's elements");
8 for i from 1 to N do
9 write("Type in the",i,"th element");
10 read("A[i]");
11 endfor
12 co The array is supposed to be sort fco
13 write("Type in the element to be sorted");
14 read(x);
15 g:=1;
16 d:=N;
17 rest:=-1;
18 while((g<=d)&&(rest==-1)) do
19 m:=(g+d)div2;
20 if(x==A[m]) then res:= m
21 else
22 if (x<A[m]) then d:=m-1;
23 else g:=m-1;
24 endif
25 endif
26 endwhile
27 if (re==-1) then write("element not found");
28 else write("element found at position:", res);
29 END

d) auto-adaptive search
This search method aims to reorganize the list of elements

B. Exercise

Exercise
Write an algorithm which read an array of 50 students names of Beng1. The
algorithm read also an array of 50 real numbers representing the Algorithm Basics
CA marks of those students. The name an students marks are read simultaneously.
The algorithm will sort the array of marks in descending order and process the
ranking in order of merit( from the highest mark to the lowest). The result should
be display as follow:

Rank Name Mark Mention

 If the mark is between 0 and 04/20, the mention to display is "weak"


If the mark is between 5 and 10/20, the mention to display is "below
average"
If the mark is between 10 and 12/20, the mention to display is "Average"
If the mark is between 12 and 14/20, the mention to display is "Fairly
Good"
If the mark is between 14 and 16/20, the mention to display is "Good"
If the mark is between 16 and 18/20, the mention to display is "Very
Good"

44
Searching and Sorting

If the mark is greater than 18/20, the mention to display is "Excellent"

45
Section
VIII-

VIII

47

You might also like