0% found this document useful (0 votes)
3 views

Chapter 3 Introduction To Algorithmics

Uploaded by

salhatlydia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 3 Introduction To Algorithmics

Uploaded by

salhatlydia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Université Badji-Mokhtar Annaba ‫جامعة باجي مختار عنابة‬

Faculté de Technologie ‫كلية التكنولوجيا‬

Première Année Ingéniorat en sciences et techniques

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.

2. General Structure of an Algorithm: An algorithm is composed of three main parts (see


the following figure):
• The header: this part is used to give a name to the algorithm. It is preceded by the word
Algorithm;
• The declarative part: in this section, the algorithm declares the various objects it uses
(constants, variables, etc.);
• The body of the algorithm: this part contains the instructions of the algorithm. It is delimited
by the words Begin and End.

Algorithm Name-Of -Algorithm;


Constants Name-of const= value;
Variables Name-of-variables :type ;

Begin
Instruction1;
Instruction2;
.
.
InstructionN;
End.

2.1. Algorithm Name :


 It simply allows identifying an algorithm among others.
 The header part of an algorithm simply allows giving a name to our algorithm. This
name does not influence the proper execution of the algorithm.
 In general, it is advisable to give meaningful names to our algorithms. This is to enable
the reader to have an idea of what the algorithm they are reading will do.

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.

The body of the algorithm:


• In this part of the algorithm, tasks to be executed (instructions, operations, etc.) are placed.
• In this part of the algorithm, tasks (instructions, operations, etc.) to be executed by our
algorithm are placed.
2.3. Les variables et les constantes :
2.3.1. Concept of Variable
Data, as well as the results of intermediate or final calculations, are stored in memory locations
corresponding to variables. Thus, a variable is stored in a memory location named, of fixed
(or not) size, taking on during the algorithm's execution an indefinite number of different
values.
In other words, a variable is a label that identifies the memory location where a value is stored
for manipulation. Although one is free to give a variable any name, it is preferable, for the
sake of readability and understanding, to choose variable names based on what they represent.
For example: Variables like Average, Weight, Height, etc.

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.

Priority and Order of Evaluation of Operators:

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.

4. Inputs/Outputs (Write/Read/Display, Input/Output)


The algorithm needs input data and provides a result as output. When using a computer, the
keyboard allows entering data, and the screen displays a result. When displaying text on the
screen, a function named Display/Write is used. This function displays on the screen the
arguments it is asked to display. We will also use another function named Read which allows
storing the data entered via the keyboard in variables.
Inputs: Read Data
Syntax: Read(<list of variable names>);
Function: Action that allows placing in memory the information provided by the user.
Examples:
Read (x);
Read (name, surname);
Read (value);
Outputs: Display Data, Result
Syntax: Write(<Expression>);
Function: Action that allows visualizing the information placed in memory.
(<Expression> can be: Text, the value of a variable, a mix of text and values, a mathematical
expression)
Examples:
 Write ("Enter the value of x");
 Write (x);
 Write ("The value of x is ", x, " and the value of y is ", y);
 Write ("The value of Delta is ", Deltab*b – 4* a* c);
Commas separate the strings to be displayed. All text enclosed in quotes is displayed as is on
the screen, whereas when a variable appears in the DISPLAY action, its value is displayed.
Example:
Algorithm Example_TTC;
/ Takes an HT price and displays the corresponding TTC price

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.

5.3. Multiple Choice Selection:


The multiple-choice selection statement uses a variable or an expression called a selector,
whose value is compared to a list of labels. In case of equality, the action block associated
with the label is executed.

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;

6. Loops (Repetitive Actions):


A loop allows you to repeat a block of actions multiple times. The process of going through a
loop is called iteration.
There are mainly three types of loops:

• For Loops: Used to repeat a block of actions a certain number of times.


• While Loops: Used to repeat a block of actions until a stop condition is met.
• Repeat-Until Loops: Used to repeat a block of actions until a stop condition is met,
with the execution of at least one iteration.

6.1. The "For" Loop:


The "for" loops allow the repetition of a block of actions a given number of times. They are
characterized by knowing in advance the number of iterations to be performed.
Syntax:
For (variable) from (Initial Value) to (Final Value) [step] (value) do
<action block>
EndFor;

Note: When the value is equal to 1, the step is optional.


Example:
For i from 0 to 10 do
write(i);
EndFor;

6.2.The "While" Loop:


While loops allow iterations as long as a certain condition is met. The number of iterations is
not known in advance, but at each iteration, the condition is checked. As soon as this condition
is false, the loop is exited.

Syntax :

While (condition) do
<action block>
EndWhile;

10
Example:
n = 1;
While (n mod 21 =!0) do
n = n + 15;
EndWhile;

6.3. The "Repeat" Loop


The "repeat...until" loop is used when you need to execute the block of actions at least once.
Syntax:
Repeat
<action block>
Until <condition satisfied>;

7. Complex Data Structures (Arrays and Records)


7.1. Arrays:
In algorithmics, an array is a data structure that consists of a collection of elements, each
identified by an index or a key. The elements are stored in contiguous memory locations, and
the key serves as a reference to access a specific element within the array. The key is typically
an integer, allowing for efficient and direct access to elements.

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.

The main characteristics of arrays include:

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.

7.1.1. Declaration of an Array


Syntax:
Variables <identifier> [SizeofArray]: type;
Example:
Variables note [12]: real; // an array variable "note" of 12 real numbers.
cases

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.1.3. Operations on Arrays:


Arrays support various operations, including:
• Searching for an Element
• Sorting an Array (Ascending or Descending Order)
• Adding an Element (at the beginning, in the middle, or at the end of the array)
• Deleting an Element

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.

Here are some key characteristics of records:

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.

7.2.1. Declaration of a Record


Syntax:
Type Record = type_name
field_name1: field_type1 ;

field_nameN: field_typeN ;
EndRecord ;

Example:
Type Record = person
Begin
name: string ;
firstName: string ;
age: integer ;
EndRecord ;

7.2.2. Access to Record Fields


While elements of an array are accessible through their index, fields of a record are accessed
through their names using the '.' operator.
Syntax:
record_name.field_name;

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

You might also like