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

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

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;

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

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

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

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

VI

35

You might also like