Chapter 3 Introduction To Algorithmics
Chapter 3 Introduction To Algorithmics
1.Introduction:
1.1. Who Invented the Algorithm?
The mark of Al-Khawarizmi in history is closely tied to that of
mathematics, particularly his contributions to algebra and geometry.
However, his name is also inseparable from computer science because
each procedure he described for solving a calculation involves a sequence
of instructions, which are manipulations on numbers. In fact, the name Al-
Khawarizmi was translated to "Algorismi" in Latin, eventually giving rise
to the word "Algorithm."
1.2. Definition:
An algorithm is a finite and unambiguous sequence of operations or instructions designed to
solve a problem. Derived from the name of the Persian mathematician Al-Khwarizmi (±820),
the father of algebra, an algorithmic problem is often formulated as the transformation of a set
of input values into a new set of output values. Examples of algorithms include:
• A cooking recipe (ingredients → prepared dish)
• Dictionary lookup (word → definition)
• Integer division (two integers → their quotient)
• Sorting a sequence (sequence → ordered sequence)
In summary, one can say:
An Algorithm: is a finite sequence of operations (a series of instructions) that provides the
solution to a given problem (aiming to solve a specific problem). To write an algorithm, a
pseudo-language is used that is understandable by a community. Thus, the general idea of an
algorithm is to present the solution to a problem in the form of operations that can be translated
into a language understandable by a machine, while still keeping it readable and
comprehensible to an ordinary person.
A Program: is a collection and sequence of elementary instructions written in a programming
language, executed by a computer to process the data of a problem and produce one or more
results.
A Programming Language: is a set of keywords and syntax rules that allow the creation of
instructions forming programs, which can be executed seamlessly on a machine. Among
programming languages, notable examples include Pascal, C, C++, Python,Visual Basic, Java,
C#, J#, etc.
1.3. Relationship between Algorithmics and Programming:
Every problem to be programmed must first be solved in the form of an algorithm and then
converted into a program in the programming language of your choice. Indeed, an algorithm
is independent of the programming language used.
A program is a sequence of instructions written in a programming language, executed by a
computer to address a problem and produce results. It represents the translation of an
algorithm using a programming language.
1.4. Concept of Algorithm in Everyday Life:
In everyday life, an algorithm can take the form of:
• A cooking recipe: starting from the ingredients, it explains how to arrive at the dish.
• A road itinerary: explains how, from an initial position, to reach a final position in a
certain number of steps.
• An instruction manuel, etc.
Example: Prepare the Pie Crust
The ingredients are:
250 g of flour;
50 g of butter;
1 glass of milk.
The elementary actions to perform:
Begin
Incorporate the butter into the flour;
Knead the mixture until it is homogeneous;
Add milk;
Mix;
If the dough is too dry, then add milk;
If the dough has a good consistency, then let it rest for half an hour;
Bake the crust;
End.
2
An algorithm serves to transmit a skill. It describes the steps to follow to accomplish a task.
Just as a chef's know-how is conveyed in the form of a recipe, that of a computer scientist is
transmitted in the form of an algorithm.
Begin
Instruction1;
Instruction2;
.
.
InstructionN;
End.
2.2. Declarations:
3
It is an exhaustive list of variables used and manipulated within the body of the algorithm.
It is a comprehensive list of objects, quantities used, and manipulated within the body of the
algorithm. This list is placed at the beginning of the algorithm.
Constants:
• They represent numbers, characters, strings, etc., whose value cannot be changed during the
execution of the algorithm.
• A constant is a part of the algorithm that allows declaring constants.
• A constant is an object whose content remains unchanged during the execution of an
algorithm.
Variables:
• They can store numbers, characters, strings, etc., whose value can be changed during the
execution of the algorithm.
• A variable is an object whose content can change during the execution of the algorithm.
4
The concept of variable type is crucial (very important) because it involves the choice of
variable encoding (for example, a 32-bit integer or a 16-bit character) as well as the
possibilities of use (for example: you cannot multiply a character by an integer).
Syntax:
Variable identifier: type;
Example of variable declarations:
Variable surface: real;
Variable a: integer;
Variable a, b, c, d: integers;
Variable Name, FirstName: string;
Variable absent: boolean or logical;
Identifier of a variable:
An identifier is the name given to a variable, function, etc. This name must necessarily start
with a letter followed by a sequence of letters and numbers, and it must not contain any
spaces.
Data Types:
The type of a variable is the set of values it can take. For example, a variable of type logical
(boolean) can take the values True or False.
The different types used in algorithms:
• Integer Type is used to manipulate positive or negative integers. For example: 5, -15,
etc.
• Real Type, on the other hand, is used to manipulate floating-point numbers. For
example: 3.14, -15.5, etc.
• Character Type allows the manipulation of alphabetical and numerical characters. For
example: 'a', 'A', 'z', '?', '1', '2', etc.
• String Type is used to manipulate strings of characters representing words or phrases.
For example: "hello", "Mister", etc.
• Logical Type (Boolean): utilizes logical expressions. There are only two boolean values
: Ture and False.
5
In algorithmics, each operator has its priority and order of evaluation. In an expression
containing multiple operators, those with higher priority are evaluated first, followed by those
with lower priority, and so on until those with the lowest priority are reached. In cases where
multiple operators have the same priority, their order of evaluation determines which one will
be evaluated first. Below is a table of priority and order of evaluation for various operators:
Examples:
What is the value of X after the following instruction? X 3 + (1 + (2 + 1) * 3) / 2 ;
What is the value of Y after the following instruction? Y 17 / 5 + 17 div 5 + 17 mod 5 ;
The instructions of the algorithmic language
It is in the Algorithm Body that most of the operations are placed.
These operations can be divided into four categories.
3. Assignment Operations:
Syntax: identifier <Expression>;
: Assignment symbol
<Expression> can be:
a value, e.g., X 5;
a variable, e.g., X Y;
an expression, e.g., Z 2*X + (Y - Z);
Assignment is always done in two steps:
6
Evaluation of the expression to the right of the symbol.
Assignment of the result to the variable identifier.
7
Constants TVA = 20.6;
Title = "Result";
Variables prixHT, prixTTC: real; / declarations
Begin / processing preparation
Write("Give me the price excluding tax:");
Read(prixHT);
prixTTC ← prixHT * (1 + TVA / 100); / calculation of the TTC price
Write(Title); / presenting the result
Write(prixHT, " D.A. H.T. becomes ", prixTTC, " D.A.T.T.C.");
End.
5. Control Structures:
Control actions are used to manage the flow of actions within an algorithm. These actions can
be either conditional or iterative.
• Conditional Actions: Tests Conditional actions enable the execution of different code
segments based on the result of tests.
5.1. Simple Conditional Action:
Syntax:
If <logical expression>
then <action block>
End if;
If the logical expression (the condition) evaluates to true, the action block is executed; if it
evaluates to false, the algorithm continues after the end if statement.
Example:
If (a=b) then
Display ("The two values are equal");
End if;
5.2. Alternative Conditional Action
Syntax:
8
If <logical expression>
then <action block1>
Else <action block2>
End if;
If the logical expression (the condition) evaluates to true, the first action block is executed; if
it evaluates to false, the second block is executed.
Example: Display "Received with honors" if a grade is greater than or equal to 12, "Passable"
if it is greater than 10 and less than 12, and "Insufficient" in all other cases.
Algorithm Example_grade;
Variables note: float;
Begin
Write (" please introduce a note ");
Read(note);
If (note >= 12 )then
Write (" Received with honors ");
Else If (note > 10) and (note < 12) then
Write( "Passable")
Else
Write ( "Insufficient");
End If;
End.
Syntax:
switch <identifier> // The identifier is either a variable or an expression
case label1: action block
case label2: action block
...
case labeln: action block
[default: action block]
end switch;
If there are more than two possible choices, the switch statement provides a convenient way
of writing.
9
Example:
switch abbreviation
case "M": Write("Monsieur");
case "Mme": Write ("Madame");
case "Mlle": Write ("Mademoiselle");
default: Write ("ERROR");
end switch;
Syntax :
While (condition) do
<action block>
EndWhile;
10
Example:
n = 1;
While (n mod 21 =!0) do
n = n + 15;
EndWhile;
Arrays are used to store and organize data of the same type, such as a list of integers,
characters, or other data types. The elements in an array are often of homogeneous data types,
meaning they share a common data type.
1. Indexing: Elements in an array are accessed using an index or key, which usually starts
from zero (0) for the first element.
2. Fixed Size: Arrays have a fixed size determined at the time of declaration. Once the size is
set, it typically cannot be changed dynamically during runtime.
3. Contiguous Memory: Array elements are stored in adjacent memory locations, which
allows for efficient access through direct indexing.
Arrays are widely used in algorithms and programming because they provide a simple and
efficient way to organize and manipulate data. They are fundamental for tasks like sorting,
searching, and storing collections of data.
11
7.1.2. Accessing Elements of an Array
In addition to declaring an array, you need to declare a variable that will act as an index,
address, or subscript for the array elements. The elements of the array are accessible through
this index, which represents the number of the array element's position.
7.2. Records:
In algorithmics, a record is a composite data type that allows you to group variables of
different data types under a single name. Each variable within a record is often referred to as
a field or a component. Unlike arrays, which store elements of the same data type, records can
store heterogeneous data types.
A record is defined by specifying the names and data types of its fields. Each field within the
record can be accessed using its unique name. This makes records useful for representing
complex data structures where each component has a distinct role or meaning.
Fields: Records consist of multiple fields, each having its data type. Fields can represent
different attributes or properties of the record.
Heterogeneous Data Types: Unlike arrays, records can contain fields with different data
types. For example, a record might include a field for an integer, another for a string, and so
on.
12
Named Access: Fields in a record are accessed by their names rather than indices. This makes
it easier to understand the meaning of each component.
Structural Organization: Records allow for the structural organization of related data,
providing a way to model real-world entities and relationships.
Example:
Type Record = person
Begin
name: string ;
firstName: string ;
age: integer ;
EndRecord ;
Algorithm Example;
Type Record = person
name: string ;
firstName: string ;
age: integer ;
EndRecord ;
Variables pers1, pers2: person;
Begin
Display("Enter the name and age of person 1");
Input(pers1.name, pers1.age);
Display("Enter the name and age of person 2");
Input(pers2.name, pers2.age);
Display("The age difference between ", pers1.name, " and ",
pers2.name, " is ");
If (pers1.age > pers2.age) Then Display(pers1.age – pers2.age, " years ");
13
Else
Display(pers2.age – pers1.age, " years ");
EndIf;
End.
14