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

Course of Algorithm and Programming

Uploaded by

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

Course of Algorithm and Programming

Uploaded by

V-Tech Community
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

BTS 1-DQP-CQP

Course title: Algorithm and Programming

Sector : GLO, IWD, RES, Infographie

Teacher: Mr. Joël Casimir TAGNE

Academic year: 2024-2025

Prerequisites:

▪ Know the step-by-step reasoning in solving society's problems;


▪ Know the DAR (Divide And Rule) paradigm for problem solving.

Objectives: The student must be able to:

▪ Systematically analyze a computer problem;


▪ Use a rigorous resolution method to solve a problem;
▪ Write an algorithm;
▪ Manipulate data structures and control structures;
▪ Execute an algorithm;
▪ Write your own functions and procedures and use them;
▪ Manipulate files and records;
▪ Translate any algorithm into Pascal language;
▪ Manipulate the functions of existing Pascal libraries;
▪ Know the notion of complexity of an algorithm.

1/ 62
Program:

Part 1 : Algorithm ............................................................................................... 6

I- Introduction ................................................................................................... 6

II- Basic concept of algorithm ........................................................................ 6

1- Definitions ................................................................................................ 6

2- Characteristics of a good algorithm ...................................................... 6

3- Stages in solving a problem.................................................................... 7

4- Representation of algorithms ................................................................ 9

5- General structure of an algorithm ........................................................ 9

III- Variable and Constant............................................................................. 10

1- Variable.................................................................................................. 10

2- Constant ................................................................................................. 11

IV- Operators .................................................................................................. 12

1- Types of operators ................................................................................ 12

2- Some special operators ......................................................................... 12

3- Order of priority ................................................................................... 12

V- Instructions ............................................................................................... 13

1- Simple instructions ............................................................................... 13

2- Running of an algorithm ...................................................................... 14

3- Algorithm execution trace.................................................................... 15

4- Control structures ................................................................................. 15

VI- Flowchart .................................................................................................. 21

1- Standardized symbols........................................................................... 21

2- Rules for constructing algorithms ....................................................... 22

2/ 62
3- Flowchart examples .............................................................................. 23

VII- Function and Procedure .......................................................................... 24

1- Procedure ............................................................................................... 24

2- Function ................................................................................................. 25

3- Parameter passing mode ...................................................................... 26

4- Scope of variables ................................................................................. 27

VIII- Data Structures ..................................................................................... 27

1- Stack ....................................................................................................... 27

2- Queue ..................................................................................................... 28

3- Array ...................................................................................................... 28

4- Record .................................................................................................... 30

5- List .......................................................................................................... 31

6- Some algorithms applied to data structures ...................................... 31

IX- Files ............................................................................................................ 32

1- Definition ............................................................................................... 33

2- File types ................................................................................................ 33

3- File organization ................................................................................... 33

4- Types of file access ................................................................................ 33

X- Algorithm complexity .............................................................................. 34

1- Definition ............................................................................................... 34

2- Algorithm complexity type .................................................................. 35

Part 2: Programming ........................................................................................ 37

I- Programming basics ................................................................................... 37

1- Programming language ........................................................................ 37

3/ 62
2- IDE concept ........................................................................................... 38

II- General structure of a Pascal program ................................................. 39

III- Symbols and separators........................................................................... 40

IV- Variable and type ..................................................................................... 41

1- Variable.................................................................................................. 41

2- Types ...................................................................................................... 41

3- Expression.............................................................................................. 46

V- Constant .................................................................................................... 46

VI- Instructions ............................................................................................... 47

1- The assignment...................................................................................... 47

2- Inputs/Outputs ...................................................................................... 48

VII- Pratical Work (PW) No 1: Discovering the IDE environment (Free


Pascal) ................................................................................................................. 49

1- Software installation ............................................................................. 49

2- Interface presentation .......................................................................... 49

3- Text editor ............................................................................................. 50

4- Using the programming environment ................................................ 51

5- The break ............................................................................................... 52

6- My first program .................................................................................. 52

7- Trace and output table ......................................................................... 53

VIII- Summary table of Pascal language elements ..................................... 53

IX- Complex types .......................................................................................... 57

1- Creating new types ............................................................................... 57

2- Interval type .......................................................................................... 58

4/ 62
3- Enumerated type ................................................................................... 60

4- Structured types (records) ................................................................... 61

5/ 62
Part 1 : Algorithm

I- Introduction

Human beings spend most of their time solving the problems they face by implementing
processes known as algorithms. Much of human reasoning is algorithm. In fact, because of
the human inability to handle too much complexity, it has been essential to find modeling
methods. In computer science, algorithms are one such method.

We can therefore ask ourselves questions such as: What is an algorithm? What is
algorithmics? How do you go about writing an algorithm? and many others.

In the rest of this course, we'll answer these questions and give some illustrative examples.

II- Basic concept of algorithm

1- Definitions

An algorithm is an ordered sequence of operations designed to obtain a given result in a finite


time.

An algorithm is a finite, ordered sequence of instructions whose step-by-step execution enables


a problem to be solved in a given time. An instruction is an elementary operation performed by
a computer. The most critical stage in designing an algorithm is understanding the problem to
be solved.

Algorithmics is the science of studying algorithms.

II enables you to:

- Describe a methodical programming approach,


- Control complexity,
- Easier maintenance,
- Reduce costs, ...

2- Characteristics of a good algorithm

When executed correctly, an algorithm leads to a given result. So, if an algorithm is right, its
result will be the desired or expected one. On the other hand, if an algorithm is wrong, the
result will be, if you like, random.

6/ 62
A good algorithm must be:

- Readable: it must be understandable, even by a non-computer scientist;


- Precise and unambiguous: no part of its code should be confusing. All ambiguities
must be removed;
- Simple and concise: an algorithm should not exceed one page in length. If it is, it
must be broken down into several sub-problems. It must have a clear set of inputs and
outputs;
- It must have an ending.
- Solve the problem.

3- Stages in solving a problem

a- Definitions

A problem can be defined as a situation in which an obstacle prevents us from progressing,


moving forward or achieving what we would like to do.

A class of problems is a set of problems of the same nature or which relate to the same thing.

b- Principle

Before designing an algorithm, it is necessary to:

- understand the nature of the problem posed and specify the data supplied (inputs)
- Specify the results to be obtained (outputs)
- Determine how the data will be transformed into results.

In algorithmics, each elementary task is described by a simple, comprehensible expression (or


word).

Example: A program is required to display the result of the equation AX+B=O on a screen.
Let's propose an algorithmic approach corresponding to this program.

Solution:

Data: A, B

Result: X

Processing: Determine X in AX+B=O according to the different possible cases.

c- Different stages in solving a problem

7/ 62
Generally speaking, an analysis of a problem with the aim of solving it can be reduced to a
series of questions:

- What do we want to achieve?


- What operations are required to achieve this result? (How is this result obtained?) What
data are needed to carry out these operations? (What do we need?)

Whatever the type of problem you're faced with, the analysis will consist of:

▪ Define the problem precisely to identify the result(s) (Output) to be obtained.


▪ Identify the processes (actions) needed to obtain the result(s) in the context of the
problem.
▪ Identify the information (Inputs) needed to carry out the treatments envisaged.
▪ Run the algorithm step by step through a set of tests to check whether it produces the
required result.

In this way, the algorithm can be presented in the following classic way:

8/ 62
4- Representation of algorithms

There are several languages for representing algorithms. These include the Algorithm
Description Language (ADL), the Flowchart Language (FL) and the Decision Table.

a- Algorithm Description Language (ADL)

It is a language that uses key words and structures to describe completely and clearly all the
operations to be performed on data to obtain a result. We generally use English or French to
represent. The advantage of this language is that it is easy to transcribe an algorithm into a
program.

b- Flowchart Language (FL)

A flowchart or algorigram of an algorithm is the graphical sequence of operations in that


algorithm. It is used to represent an algorithm schematically. The normalization symbol is
generally used to represent.

c- Decision table

This is a tool used much more in conditional branching. It uses a table composed of two parts:

- The part reserved for the conditions;


- The part reserved for actions or instructions.

NB: The rest of the course, when we talk about algorithms without specifying a representation
language, we will use the default Algorithm Description Language (ADL).

5- General structure of an algorithm

An algorithm essentially includes 03 parts:

- The header: This simply identifies the algorithm.


- The declarative part: Used to declare all the objects to be used in the body of the
algorithm, i.e. variables, constants, functions, procedures, etc.
- The body of the algorithm: Between the "BEGIN" and "END" keywords, it
contains instructions, delimiters, processing operations and comments.

The general syntax of an algorithm is as follows:

9/ 62
Algorithm algorithm _name Header

Declaration of constants;

Declaration of variables;
Declarative part
Declaration of procedures;

Declaration of functions;

Begin

Instruction 1;
Body of the algorithm
Instruction 2;

….

Instruction n;

End

III- Variable and Constant

1- Variable

A variable is an object whose value can change during the execution of the algorithm.

A variable is mainly characterized by:

❖ An identifier: this is the name of the variable. It is made up of letters and numbers.
❖ A data type: this is the nature of the variable used. There are 05 basic types: Integer
(1; 2; 3;…), Real (0.1; 2.5; 10.0;…), Character ('a'; 'b'; 'z'; '+'; '1' ; …), String
(''mom''; ''dad''; ''237''; ''toto2023'' ; …), Boolean (true and false / yes and no
/ 0 and 1).
❖ A value: this is the value taken by the variable. This value depends on the data type
of the variable. This value may be the result of processing.
❖ An identifier: this is the name of the variable. It is made up of letters and numbers.
❖ A data type: this is the nature of the variable used. There are 05 basic types:
- Integer: Values associated with this type are integers. Example: 10, 12, -3, ...

10/ 62
- Real: These are real numbers. A dot (.) is used to separate the integer part from the
decimal part. Example: 10.1; 11.55; 0.5
- Character: contains all common characters. Letters, numbers and special
characters (dot, comma, operators [,], +, *, -, /, <, >, &, $, {,}, (,), ...). The
apostrophe character (') is surrounded.
- String: A string must have at least two characters. The characters in a string are of
type character. The string is surrounded by a double quotation (''). Example:
''maman''; ''papa''; ''237''; ''toto2023''; ...
- Boolean: There are two possible values: true and false.
❖ A value: this is the value taken by the variable. This value depends on the variable's
data type. This value may be the result of processing.

To use a variable, it must be declared. The keyword for declaring a variable is “Var”. The
syntax is as follows Var variableName: Type;

Example: Var Number: Integer; Var Name: String; Var a: Real;

Remark: variables can be grouped into 03 categories according to their usefulness:

❖ Input variable: any variable used to retrieve the input data of a problem.
❖ Output variable: any variable used to retrieve (return) the results of a problem.
❖ Internal variable: any variable used in addition to the others when solving a problem.

2- Constant

A constant is an object whose value does not change during the execution of the algorithm. A
constant is characterized by:

❖ An identifier: this is the name of the constant. It is made up of letters and numbers.
❖ A value: this is the value taken by the constant. This value is fixed.

To use a variable in an algorithm, you need to declare it. The “Const” keyword is used to
declare a constant.

The syntax is as follows: Const constantName = valuer;

Example: Const rating = 4; Const Name = "Touza Isaac"; Const pi = 3.14; Const a=10;

Remark: A constant is a variable whose value is fixed.

11/ 62
IV- Operators

When writing an algorithm, we often use operators to translate mathematical operations.

1- Types of operators

The operators used in an algorithm can be grouped into several categories including:

❖ Arithmetic operators: + (addition); - (subtraction); * (multiplication); / (real


division).
❖ Comparison operators: < (less than); <= (less than or equal to); > (Greater than);
>= (Greater than or equal to); = (Equal to); <> (difference).
❖ Logical operators: AND, OR, NOT.

❖ Functions: div (integer division); mod (the remainder of dividing one integer by
another), ^ (exponent).

NB: The operators / and div are used for division, one for dividing real numbers and the other
for dividing integers.

2- Some special operators

These are called predefined functions.

Examples: sqrt(9), abs(-4), sin(45),cos(90), power(3,5).

3- Order of priority

To run an algorithm containing mathematical operations, you need to know the order in which
the operators will be executed, so as not to make mistakes when running the algorithm.

The order of priority is the order in which operators are executed in a numeric expression.

The operators below are ordered from highest priority to lowest priority in the evaluation of a
numeric expression:

- Brackets;
- Functions (div or mod or ^);

12/ 62
- The multiplication (*) and division (/) operators;
- The addition (+) and subtraction (-) operators.

Remark: If the order between operators in an expression is the same, then the expression is
evaluated from left to right.

Example: 4*5/2*2 = 20/2*2=10*2=20;

(2*4) / 2+ 8 mod 3 = 8/2+2= 4+2 = 6

V- Instructions

Instructions are the processing commands that respect the simple actions in the execution of an
algorithm. A statement always ends with a semicolon (;).

The syntax of an instruction is as follows: Instruction;

There are several types of instructions in an algorithm, among which we cite:

❖ Object declaration instructions;


❖ Instructions for use of declared objects;
❖ Simple instructions;
❖ Control structures.

1- Simple instructions

There are 3 types of simple instructions in algorithms:

a- Read (or enter) instruction

It allows you to retrieve the data entered by the user and stores it in a variable. It therefore uses
an input device (usually the keyboard) to perform this task. It is used with the “Read()”
keyword.

The usage syntax is as follows: Read(variableName);

Example: Read(a); Read(name);

b- Write (or output) instruction

It allows you to display a message or the content of a variable on an output device (generally
the screen). It is used with the “Write()” keyword.

13/ 62
The usage syntax is as follows:

Write(“message to display’’);
or
Write(variableName);

Example: Write(“Hello students”); Write(name);

c- Assignment instruction

It allows you to assign a value to a variable. It is used with the symbol ''←''.

The usage syntax is as follows: variableName ← value;

Remark: The expression A←B reads “A takes the value B” or “to A we assign B”. The result
is to put the contents of variable B into variable A.

There are 04 types of assignment instructions:

❖ Increment instruction: it allows you to increase the value of a variable by “1”.


The usage syntax is as follows: variableName ← variableName + 1;
Example: a← a+1; k← k+1 ;
❖ Decrement instruction: it allows you to decrease the value of a variable by “1”.
The syntax is as follows: variableName ← variableName - 1;
Example: ja← ja-1; x← x-1;
❖ Initialization instruction: it allows you to assign a number or a character or a
character string to a variable.
Example: y← 100; letter←' a’; name←''toto'';
❖ Simple assignment instruction: this is one that is neither an increment nor a
decrement nor an initialization instruction.
Example: y← y*9; k←(k+l)/p; a←b+1;

2- Running of an algorithm

Given that an algorithm is a sequence of instructions arranged in a certain order, executing an


algorithm means executing each of the instructions that make up the algorithm one by one,
and above all respecting the order in which the instructions are written, in order to find out
what result the algorithm produces.

The running of an algorithm is carried out line by line respecting the following principles:
14/ 62
- Assigning values to the variables and constants declared in this algorithm and
replacing each variable with its value during execution then perform the operations.
- Respecting the order of priority of operators to perform arithmetic operations.
- Storing the contents of the variables at each step of execution of the algorithm.
- The return of the contents of the output variable at the end of the execution of the
algorithm.

3- Algorithm execution trace

Application:

Run the following algorithm with the values a = 2, b = 5 and c = 8:

Algorithm Example

Var a, b, c, s: Integer;

Begin

Read(a);

Read(b);

Read(c);

s← (a+b) mod a * c / a *b;

Write("The final value of s is:", s);

End.

4- Control structures

Control structures enable the computer to perform more complex actions. They make it possible
to control the execution of tasks in an algorithm.

Depending on their sequence, control structures can be organized into four fundamental
families of algorithmic structures:

- Sequential structure;
- Alternative structure;
- Multiple choice structure;
- Iterative structure;

15/ 62
a- Sequential structure

Also called a linear structure, it allows instructions to be executed one after the other (line by
line). This was the first model for the execution of instructions by a computer, and was
developed by John Von Neumann.

b- Alternative (conditional) structure

We want to execute one action or another depending on whether a test is true or false. There
are two main types of alternative structure, as shown in the table below:

1) Simple conditional structure 2) Complete conditional structure

If (condition) then
If (condition) then Instruction blocks 1;
Syntax: Instruction blocks; Else
EndIf Instruction blocks 2;
EndIf
❖ The condition is evaluated;
❖ The condition is evaluated; ❖ If the condition is True, the 1st
❖ If the condition is True, the block of instructions will be
Functioning: instructions are executed; executed;
❖ If the condition is False, the ❖ If the condition is False (else), the
instructions are not executed. 2nd block of instructions will be
executed;

16/ 62
False
IF
False
IF
True

Flowchart: THEN
True
Leap
THEN
ELSE
Else
ENDIF

ENDIF

Example:

If x < 0 then

Write(''the absolute value of x is:'', -x);

Else

Write (''the absolute value of x is:'', x);

EndIf

Remarks:

- The conditional structure can be imbibed.


- The alternative structure can be extended to include more than two possible choices.

The syntax is as follows:

If (condition 1) then

Instruction blocks 1;

Else If (condition 2) then

Instruction blocks 2;

…..

17/ 62
Else

Instruction block n;

EndIf

c- Multiple choice structure

This is a conditional structure used to select a block of instructions to be executed from several
choices at once.

Syntax:

Switch (selector) Do

Case value 1: instruction block 1;

Case value 2: instruction block 2;

…..

Otherwise: instruction block n;

Endswitch

The selector can be a scalar variable or an arithmetic or logical expression.

The “Switch” structure evaluates the "selector", comparing it with the values in the lists. If
there is a match with a value, the corresponding actions in front of that value will be executed.

In front of “Case”, there can be a single value, a series of values separated by commas and/or
an interval of values.

After processing the corresponding sequence of actions, execution continues after the
“EndSwitch.”

Remark: The selector must have the same type as the values in front of the cases.

d- Iterative (repetitive) structure

It allows a block of instructions to be executed several times.

The instructions are repeated a certain number of times. The repetition may or may not be
known.

An iteration or loop is a sequence of instructions designed to be executed several times.

18/ 62
A cycle is a turn of the loop. There are two types of loops:

❖ The loop having the number of iterations known in advance:

This loop is called the “For loop”. It allows you to execute an instruction block several times
according to a fixed number of iterations.

It performs the same processing for a range of integer values between a lower bound and an
upper bound. Since the update is automatic, processing of the “For” loop stops when one of
the limits is exceeded.

Syntax:

For counter from val_initial to val_final Do

Instruction blocks;

EndFor

With:

- Counter: integer type variable;


- Val_initial: initial value that the counter will take;
- Val_final: final value that the counter will take.

Example:

For i from 1 to 10 Do

Write(''give a number'');

EndFor

❖ The loop whose number of iterations is not known in advance:

There are two types here:

- The While…. Do loop

It allows you to execute a block of instructions several times when the condition is True.

Syntax:

While (condition) Do

Instruction blocks;

19/ 62
EndWhile

Example:

i=1;

While i < 5 do

Write(“hello everyone”);

i ←i+1;

EndWhile

- The Repeat…Until loop

In this structure, the block of instructions is executed a first time then its repetition continues
until the condition is True. It is a structure in which processing is executed once before testing
and the number of iterations is not known.

Syntax:

Repeat

Instruction block;

Until (condition)

Example:

hour =10;

Repeat

Write(''It's not time'');

hour ←hour+1;

Until (hour = 12)

20/ 62
Flowchart of iterative structures

VI- Flowchart

The Flowchart is the graphical representation of the algorithm. It allows each elementary
operation to be represented using a standardized graphic symbol. A well-represented flowchart
must be arrowed and closed, between a “Start” and an “End”, and must make it easy to follow
the order of execution of the rules for solving the problem studied.

NB: The general direction of the connecting lines must be:

- From top to bottom;


- From left to right;
- When the general direction cannot be respected, arrowheads straddling the line indicate
the direction used.

To construct a flowchart, we use standardized symbols given below:

1- Standardized symbols

21/ 62
2- Rules for constructing algorithms

- The flowchart must be clear, concise and readable;


- The flowchart should be constructed in such a way that the reading proceeds vertically;
- Test outputs should not be reversed within the same flowchart;
- Connecting lines between symbols must not intersect;
- A connecting line must always arrive at the top and center of a symbol;
- If the flowchart appears to be complex, it should be broken down so that it is simple;
- Comments are generally placed on the right of the flowchart while the level reference
is on the left.

22/ 62
3- Flowchart examples

a- Example 1: sum of two numbers

Begin
Algorithm Somme
Var Real ;
Real ; Read(a,b)
Begin
Write (’’enter the first number’’);
Read(b); S←a+b

Write (’’enter the second number’’);


Read(a);
Write(s)

Write(s);
End End

b- Example 2: square root of a number

Algorithm Squart
Real ; Start
Begin
Write (’’enter a number’’);
Read(x)
Read(x);
IF x >=0

Write
ELSE
Write(’’No solution’’);
ENDIF No solution

End

End

23/ 62
VII- Function and Procedure

A sub-algorithm is a set of instructions performing a certain number of tasks based on a certain


amount of data. Sub-algorithms make it possible to reduce the size of algorithms, make
algorithms easier to read, facilitate error correction, etc.

There are two types of sub-algorithms: procedures and functions.

1- Procedure

A procedure is a sub-algorithm autonomously ensuring the resolution of a particular task. This


task can then be repeated in the main algorithm or in another sub-algorithm by simply calling
the procedure.

a- Declaration of a procedure

The procedure begins with the reserved word procedure followed by the procedure name and
a list of parameters enclosed in parentheses.

The parameters are input variables of a sub-algorithm. They ensure communication between
the different modules of an algorithm.

The syntax of a procedure is as follows:

Procedure procedureName (parameter1:type1, parameter2:type2……parameterN: type n)

Declaration of constants;

Declaration of variable;

Begin

/*Procedure body*/

EndProc

Remark: a procedure can have no parameters.

b- Calling a procedure

After declaring a procedure, you must use it.

A procedure call is the instruction to use a procedure in an algorithm.

When calling a procedure, the parameters are called arguments.

24/ 62
A certain number of rules must be respected:

- The arguments must appear in the order chosen during the declaration.
- Arguments must be of the same type as the parameters they represent.

The syntax for using a procedure is as follows:

procedureName(value1, value2, …., valueN);

Example:

Procedure Addition(a: Real, b: Real)

Var s: Real;

Begin

s ← a + b;

Write(''The sum is equal to:'', s);

EndProc

2- Function

A function is a sub-algorithm that performs a task and returns a result. Just like procedures,
functions can contain parameters, which will be retrieved by the function and which will be
used to execute the task.

a- Declaration of a function

The syntax for declaring a function is as follows:

Function functionName(parameter1: type1, parameter2:type2, …, parameterN:typeN):Type

Declaration of constants;

Declaration of variable;

Begin

/*Function body*/

Return (variableName);

EndFunc

25/ 62
b- Calling a function

The syntax for using a function is as follows:

variableName←functionName(value1, value2, …., valueN);

Example:

function Addition(a: Real, b: Real): Real

Var s: Real;

Begin

S←a+b;

Return s ;

EndFunc

Remark: We say that a function is recursive when it calls itself.

Example: Consider the function defined in ℕ the following:

0 𝑖𝑓 𝑛 < 1
𝑓(𝑛) = {
𝑓(𝑛 − 1) + 2 𝑒𝑙𝑠𝑒

Function Recc (n: Integer): Integer

Begin

If 𝑛 < 1 then

Return 0;

Else

Return (Recc(n-1)+2);

EndIf

EndFunc

3- Parameter passing mode

There are two types of parameters: formal parameter and effective parameter.

26/ 62
A formal parameter is the definition of the number and type of values that the sub-algorithm
must receive to execute correctly. We declare the formal parameters during the declaration of
the sub-algorithm. Formal parameters can be of any type.

An effective parameter is a real value received by the sub-algorithm during the execution of
the algorithm. The effective parameters are the parameters with which the function is actually
called.

There are two modes of passing parameters: by value and by reference (address or variable)

- Passing of parameters by value: the value of the effective parameters is copied into
the local variables resulting from the formal parameters of the called sub-algorithm. The
content of the effective parameters is not modified by the instructions of the sub-
algorithm because we work with a copy of the variable.
- Passing parameters by reference: here we use the memory location of the variable,
that is to say that the formal parameter replaces the effective parameter during the
execution time of the sub-algorithm and transmits its new value to it at the exit. We use
the keyword var.

4- Scope of variables

The place where a variable is declared is very important because it determines in which sub-
algorithm(s) it can be used.

A local variable is a variable that is defined in a sub-algorithm. It is only visible in this sub-
algorithm.

A global variable is a variable that is declared at the declaration part of the algorithm. It is
visible throughout the algorithm and in its different sub-algorithms.

VIII- Data Structures

A data structure is a type of variable made from other types of variables, usually the base
types. It allows you to store several data at the same time compared to the variables.

There are several types of structural data including: stack, queue, array, record, list, graph,
trees, etc.

1- Stack

The stack is a data structure, which allows data to be stored in LIFO (Last In First Out) order.

27/ 62
A single port stack, data is added or subtracted through the port head called the top of the
stack.

The main operations performed on a stack are:

- Test if the battery is empty;


- Stack an element: this involves putting an element at the top of the stack;
- Unstack an element: this involves removing the element at the top of the stack.

2- Queue

A Queue is a data structure in which data is stored in FIFO (First In First Out) order.

The main operations performed on a file are:

- Test if the file is empty;


- Thread an element: This involves putting an element at the top or queue of the file;
- Define an element: this involves removing the element from the file.

3- Array

An array is a data structure for storing elements of the same type. An array is a data structure
that allows you to store a fixed number of elements.

Tables are generally characterized by:

- An identifier: this is the name of the table.


- The type: all elements of the array have the same basic type;
- The size (or dimension) of the array: this is the total number of elements that the array
contains;
- indexes: these are numbers that identify the position of an element in the table. Access
to an array element is done using its indices.

Remarks:

- An array element is a value from a location (cell) in the array.


- The declaration of a table is done in the declarative part.

a- One-dimensional array

Also called a vector, it is an array in which access to an element is done using an index. It is
made up of a finite number of contiguous boxes located in central memory.

28/ 62
The following diagram presents a graphical representation of a vector named “T” of length 5:

T
1 2 3 4 5

Index

The syntax for declaring a one-dimensional array is:

Var arrayName = array[Ind_init … Ind_fin] : type ;

ou

Var arrayName = array[size] : type ;

Example: Declare a table named “Tab” allowing you to store the ages of 10 babies in a
maternity ward.

Solution: Var Tab = array[1…10]: Integer;

Or Var Tab = array[10]: Integer;

b- Multi-dimensional array

Also called a matrix, it is an array in which access to an element is done using several indices.

The syntax for declaring a two-dimensional array is:

Var arrayName = array [Size1][Size2]: type;

Example: Declare a two-dimensional array allowing you to store the distance of 09 vectors of
the plane (Ρ)whose coordinates are given by the couple (𝑥, 𝑦).

Solution: Distance Var = array [3][3]: Real;

Remarks: In a table, you can perform the following operations:

▪ Assignment operation: allows you to assign a value to an element of the array. We


can also assign an array element to a variable.
Example: Note[0] ← 7; a ← Note[5] ;b ← T[1][5] ;
▪ Read operation: it allows you to retrieve the data entered by a user and store them in
a location (box) in the table.
Example: Read(Note[1]); Read(Note[3]); Read(T[3][2]);
▪ Write operation: it displays the elements of an array.

29/ 62
Example: Write(Note[9]); Write(Note[6]); Write(T[0][0]);

4- Record

A record is a data structure for storing elements of different types.

The recordings are generally characterized by:

- An identifier: this is the name of the recording.


- Fields: a field is a property of a record. This is a variable and has a type.

The registration type declaration is done as follows:

nameRecord = Record

fieldname1: type1;

fieldName2: type2;

fieldNameN: typeN;

End nameRecord

Example: Declare a type of record allowing information to be stored on a student characterized


by name, surname, grade and gender.

student = Record

name: String;

surname: String;

gender: Character;

grade: Real;

End student

Remarks:

- The declaration of a record type is done just after that of the constants in the declarative
part of an algorithm.
- Once a record type is created, it must be used. Therefore, a variable of this type must
also be declared.

30/ 62
Example: Declaration of a variable “e” of type “Eleve”.
Answer: Var e: Eleve;
- The use of a record type variable is done with the dot (.) as follows:
variableName.FieldName
Example: With the variable “e” from the previous example, we can have the following
uses: e.grade ←15; Read(e.name); Write("the student name is:", e.name);

5- List

A linked list is a set of cells linked together by pointers. Each cell is a structure containing the
following fields: one or more data as in any structure; a next pointer to the next cell.

Linked lists are data structures similar to arrays except that an element is accessed by a pointer
instead of an index. Each element being identified by its neighbors to which it is connected.

A list being completely defined by:

- Head: it is a pointer to the first element;


- Next: each element has a pointer to another node;
- Value: value(s) of the data(s) of a node;
- End: The next pointer of the last element must point to NULL (the end of the list)

6- Some algorithms applied to data structures

Since data structures can store multiple pieces of data, they generate interest in handling
particular tasks for problem solving. As a result, several algorithms have been developed as
solutions to the problems of:

- Searching for an element in a data structure;


- Ordering elements in a data structure.

a- searching of elements

Several algorithms have been set up with the aim of searching for the elements of a data
structure, among which we cite:

➢ Sequential search

This simple method consists of traversing a structure starting from the first element, and
stopping as soon as we find the element sought (we are not looking for all occurrences of an
element).

31/ 62
➢ Dichotomous search

It is more used in a table. This method applies if the table is already sorted and uses the Divide
and Rule (DAR) technique.

Its principle is as follows: compare the desired element with the value of the box in the middle
of the table if the values are equal, the task is accomplished, otherwise we start again in the
relevant half of the table.

b- Ordering elements

Ordering consists of selecting elements and arranging them according to one or more specific
criteria. “Sorting algorithms” were developed to solve this problem.

A sorting algorithm is an algorithm that allows you to organize a collection of objects


according to a determined order relationship.

You can sort according to the order: ascending, descending or alphabetical.

There are several sorting methods (algorithms) which differ in their complexity of execution
and their decreasing complexity of understanding for the programmer:

- Bubble sort;
- Quick sort;
- Insertion sort;
- Merge sort.

IX- Files

To be executed, algorithms need to be translated into programs written in certain programming


languages, such as C, C++ and Java.

The information used in all our programs can only come from two sources: either it is included
in the program itself, or it is entered or captured by the user along the way.

Once the program is terminated, this information is lost. If we run the program again, we have
to re-enter the same or other information. On the other hand, all this information has one thing
in common: it all resides in the computer's main memory. This means that deleting the memory
(whether intentionally or not!) destroys this information.

32/ 62
It is sometimes necessary to retain certain data after program execution, for archival backup or
future use.

These considerations lead us to introduce the notion of file.

In everyday life, for example in a library, a doctor's surgery or a government office, a file is a
collection of cards with the same appearance and an unlimited number of entries.

In computing, a file is a coherent set of information (data or records, the number of which is
not known a priori) recorded on a storage medium.

1- Definition

A file is a structured set of data of the same type, named and stored on a computer-readable
medium (hard disk, floppy disk, flash disk, CD ROM, etc.).

A file can contain characters (text file), programs or values (data file).

2- File types

There are two types of files:

- (Typed) data files (File Of): are perfectly formatted files, i.e. they can be used to
directly read and write structured variables containing several data fields.
- Text files: are written in text format (strings, numbers).

3- File organization

The organization characterizes the ways in which information or records are implemented in
the file, and provides access properties.

There are two types of file organization:

- Sequential organization: we can only access records by browsing them one after the
other.
- Relative (direct) organization: A relatively organized file is made up of a number of
contiguous records of the same size, identified by a serial number.

4- Types of file access

These are the methods used to read or write a record in a file. There are two types of files:

33/ 62
- Sequential access: to read a particular piece of information, you need to read all t h e
information before it.
- Direct access: We can access the desired information directly, by specifying the
location number (sequence number) of the information.

X- Algorithm complexity

Every computer problem requires an algorithm for its solution; however, several algorithms can
be distinguished for solving the same problem, so it's often a question of choosing the most
efficient algorithm. You might think that the best way to measure the efficiency of these
algorithms would be to implement and test them on your own computer; curiously enough, this
is not usually the case. For example, if two programmers implement two different algorithms
and measure their speed each on their own computer,

whoever has the most powerful computer is likely to think he has the fastest algorithm, even if
this is not the case.

The term "complexity" is a little misleading; you might think it's a difficulty to understand, but
it's really about efficiency, and "complex" doesn't mean "complicated".

The efficiency or performance of an algorithm depends on its ability to minimize certain very
important criteria, such as:

- Runtime;
- Memory space used ;
- Network bandwidth.

Often, the same problem has several solutions described by different algorithms. To compare
these algorithms, we need to study their complexity.

1- Definition

The complexity of an algorithm is an estimate of the cost of executing it in terms of time (time
complexity) or memory space (space complexity).

Execution speed depends on the machine running the algorithm. But we'll concentrate here on
the cost of the actions resulting from the algorithm's execution, as a function of the size n of the
data processed. In particular, this enables us to compare two algorithms solving the same
problem.
34/ 62
Time complexity is an estimate of computation time;

Spatial complexity is an estimate of the memory space required by the calculation.

2- Algorithm complexity type

a- Complexity at best

The best case corresponds to the arrangement of input data for which the algorithm executes
as quickly as possible: this is the most favorable situation. It is also a minority of the possible
execution time for all possible inputs to a same size. It corresponds, for example, to the search
for an element located at the first position in a list, or to the sorting of an already sorted list.

b- Case-based complexity

Also known as expected complexity, this is an evaluation of the average execution time for all
possible inputs of the same size, assumed to be equiprobable. It differs from worst-case
complexity by considering not the maximum number of elementary instructions, but the
average number of elementary instructions over all inputs of size n. This measure often only
approximates the real data space, as it is very difficult to propose a model of "real" data. For
example, it is often assumed that all data of the same size are equiprobable, which is unrealistic.
Complexity by means of cases is more understandable in practice than in theory.

c- Worst-case complexity

The worst case corresponds to the arrangement of input data for which the algorithm executes
as slowly as possible: this is the most unfavorable situation. It is a majorant of the possible
execution time for all possible inputs of the same size, i.e. the greatest number of operations the
algorithm will have to perform on a set. It corresponds, for example, to searching for an element
in a list when it is not there, or sorting a list in ascending order when it is sorted in descending
order.

Remarks:

- When we talk about the complexity of an algorithm without specifying which, we're
often talking about its worst-case time complexity.
- Complexity, at its best, is not widely used;
- Average complexity is, in a way, the best indicator of the algorithm's "real" behavior,
provided that a model of the data distribution is available, but of course it doesn't

35/ 62
guarantee anything about the worst case ... and it's often hard to calculate, even
approximately! Calculating it may require non-elementary mathematical techniques.

36/ 62
Part 2: Programming

I- Programming basics

1- Programming language

Computer programming is all the activities involved in writing computer programs.

Programming is the translation of an algorithm into a programming language. The terms


implementation and coding are often used by computer scientists to refer to this.

The notions of algorithm and program are related, but should not be confused.

Programming language is a set of words and symbols used to write a program. A


programming language is implemented by an automatic translator called a compiler or
interpreter, which first transforms a source code written in a programming language and
executed by a computer (machine language).

A program is a sequence of instructions written in a language called machine language, which


consists solely of 0s and 1s, and is the only language understood by a computer. For example,
word processors and instant messengers are programs. The role of a programmer is to write a
sequence of instructions to be executed by the computer when a user starts a program. For
obvious reasons, it's very difficult to write a program in machine language. The programmer
therefore uses a language called programming language, which is an intermediary between
natural language and machine language.

A program can therefore really be defined as a sequence of instructions written in any


programming language, enabling one or more tasks to be carried out. Or a set of operations
designed to be executed by the computer.

A compiler is an application that transforms the source code of a program into a machine-
executable binary file.

Code is the text of a program.

There are thousands of computer programming languages, and these programming languages
can be grouped into two types:

- Low-level language: Machine language is the most basic. The code of an algorithm
in machine language is not very readable (understandable), it translates the

37/ 62
operations to be carried out by the computer. It's a sequence of 0 and 1 associated with
elementary instructions that can be executed by the microprocessor. The major
drawback of this type of language for a computer scientist is its lack of legibility, which
necessarily hinders code comprehension and modification. Fortunately, there are more
advanced languages such as Assembler, which is a little more readable and often used
to code elementary instructions for the microprocessor.
- High-level languages: These higher-level languages are widely used. They give a very
high level of comprehension to anyone who has mastered their syntax. However, these
advanced languages are not suitable for direct microprocessor execution of the
underlying elementary instructions. A translation into machine language is therefore
necessary. A compiler is used to translate the program into machine language.
Examples of such languages include: Pascal, C, C++, Python, Visual Basic, Fortran,
COBOL, Java, web languages (HTML, CSS, JAVASCRIPT, PHP), etc.

Each programming language has its own specificities, with some offering certain features and
others not.

Example compilers: GNU Assembler, Turbo Pascal, Turbo C, GNU Pascal,

Delphi, javac, GCJ (Gnu Compiler for Java), Jikes, Visual Basic, FreeBasic. To

write programs, you need to install various tools.

- The first and most important step is to install a compiler.


Some compilers are already available on several operating systems, while others are
system- specific. The best-known desktop compilers include GCC (for Windows,
Android and Linux) and Microsoft Visual Studio (MSVC).
NB: Each programming language has its own compiler. For example, Turbo Pascal,
Delphi for Pascal and Javac , GCJ for Java.
- Other compilers are integrated into Integrated Development Environments (IDE).
Simply check them off when you install your IDE.

2- IDE concept

In computer programming, an IDE (Integrated Development Environment) is a set of tools


designed to enhance the productivity of software developers.

38/ 62
It consists of:

- A text editor for programming;


- A link editor;
- A debugger, which executes the program being built line by line.

Some examples of IDEs: Code::Blocks, Visual Studio, Qt Creator, Dev C++, Dev Pascal,
Eclipse ; Android Studio ; Dr Java ; My Eclipse ; J Developer...

II- General structure of a Pascal program

The code below shows the general structure of a program written in Pascal:

Program identificateur; Header

Declaration of constants;

Declaration of variables;
Déclaration
Declaration of functions;

Declaration of Procedures;

Begin

Instruction 1;

Instruction 2;
Program body
...

Instruction N;

End.

▪ The "Header" section. Every program must begin with the keyword program,
followed by the name (identifier) you want to give it: this must be the first line of your
file. This name may be different from that of the file containing your code, and must be
written in accordance with the identifier rules. Finally, this first line is terminated by a
semicolon (;).
▪ Example: Program essai ;

39/ 62
▪ In the "Declarations" section, all the objects (variables, constants, functions,
procedures, etc.) that will be used in the program must be described.
▪ Finally, the "Program body" section. Every program must contain a Begin and an
End, between which instructions are placed. This block is called the main program, and
the "End" marks the end of the program. The line containing the "End" ends with a
period (.).

After compilation, program execution consists of sequentially executing each instruction in


the main program until the "End" is reached.

III- Symbols and separators

A Pascal program is made up of symbols and separators. Separators include blanks (one or
more spaces, tabs), line breaks and comments.

Comments are texts that can be understood by humans, but which will not be read by the
machine. To indicate that a text is a comment, enclose it in braces { }, or enclose it in asterisks
(* *).

Example: the following code shows the different ways of writing a comment in Pascal:

There are different types of symbols: special symbols, keywords, identifiers, numbers,
strings, ...

Here's a list of the special Pascal language symbols we'll be using (we'll look at their meanings
later):

40/ 62
Similarly, the keywords of the Pascal language (in the program) are:

Remarks:

- At least one separator must appear between two identifiers, keywords or numbers;
- No separator should appear in a Pascal symbol.

IV- Variable and type

1- Variable

A variable is an area in the computer's random access memory, designated by an identifier and
having a type. The name (identifier) of the variable allows access to the contents of the memory
area; the type specifies the nature of what can be stored in the memory area (integer, real, char,
etc.). The size of a variable's name (identifier) depends on the type of value it contains

Every variable used in a program must be declared, i.e. all the variables required must be
named and assigned a type using the var keyword.

NB: All variables must be declared after the var keyword.

Syntax: var identifier: Type;

2- Types

A type describes a set of values that can be manipulated by a set of operators. We're going to
look at a few simple types (sometimes called predefined types).

a- Integer type

Integer type values are a subset of relative integers whose values are defined over an interval.
Exceeding the values of this interval will result in an error at runtime (and sometimes even at
compile time).

These are integers signed in 2's complement on 16 or 32 bits:

41/ 62
- On 16 bits (Turbo Pascal), the values are in [-32 768 ... +32 767] (-215 ... + 2).15−1

- On 32 bits (Delphi), values are in [-2 147 483 648 ... + 2 147 483 647] (-231... +231−1).

Example: Here are some correct examples of integer numbers: 0; 1; 32000; -56.

Let x and y be two integers, the integer operators are:

▪ +x: Unary identity operator


▪ -x: Unary operator for the opposite sign
▪ x + y: Addition
▪ x - y: Integer subtraction
▪ x ∗ y: Multiplication
▪ x / y: Real division.
If y is zero, there will be an error at runtime.
The result of x/y is a real quotient.
▪ x div y: Integer division.
If y is zero, there will be an error at runtime.
The result of x div y is an integer quotient.
▪ x mod y: Modulo.

If y is negative or zero, there is an error at runtime. The result is the remainder of the integer
division of x by y

Remark: When a value (or intermediate result) exceeds the bounds during execution, we get
an error called arithmetic overflow.

The predefined integer functions are:

- abs(x): Calculates the absolute value of x (|x|).


- sqr(x): Calculates the square of x (x2 = x ∗ x).

b- Real type

Values of real type are a subset of real numbers whose values are defined over an interval.
The real type covers values in the interval [2.9E-39; 1.7E38] in both negative and positive real
numbers, with a precision of up to 11 or 12 significant digits. Note that there are no spaces

42/ 62
between the digits, and above all that the decimal separator, which in French is the comma (,),
is here the dot (.).

Example: Here are some correct examples of real numbers: 0.0; 1E0; -1.5E4.

Let x and y be two reals, here are the operators of type real:

▪ +x: Identity
▪ -y: Opposite
▪ x + y: Addition
▪ x - y: Subtraction
▪ x ∗ y: Multiplication
▪ x / y: Real division. If y is zero, there is an error at runtime

There are also predefined functions that take a real as parameter:

- abs(x): Calculates the absolute value of x (|x|).


- sqr(x): Calculates the square of x (x2 =x ∗ x).
- sin(x): Calculates the sine of x, with x in radians.
- cos(x): Calculates the cosine of x, with x in radians.
- exp(x): Calculates the exponential of x (ex).
- ln(x): Logarithm of x.
If x is not strictly positive, there will be an error at runtime.
- sqrt(x): Square root of x.
If x is strictly negative, there will be an error at runtime.
- arctan(x): Principal value in radians of the arc tangent of x expressed in radians.

c- Char (Character) type

The character set comprising letters, digits, space, punctuation, etc. is encoded on an unsigned
byte.

The choice and order of the 256 characters depends on the machine and the language. On PCs,
the ASCII code is used, where 'A' is coded by 65, 'B' by 66, 'a' by 97, ' ' by 32, '{' by 123, etc.

The ASCII code is organized as follows:

- Control characters are coded from 0 to 31 (7 for beeper, 13 for line feed, etc.).
- From 32 to 127, standard and international characters and punctuation are encoded.

43/ 62
- Finally, from 128 to 255, accented characters specific to the language and semi- graphic
characters are coded.

The operators on the tanks are:

▪ ord(c): sequence number in coding; in this case "ASCII code".


▪ chr(a): the result is the character whose ascii code is a.
▪ succ(c): character following c in ASCII order. chr(ord(c)+1)
▪ prec(c): character preceding c in ASCII order.

Remarks:

- A runtime error occurs if the character does not exist.


- We can replace chr(32) with #32, but not chr(i) with #i.
- The apostrophe character is noted '' ''.

d- Boolean type

The boolean type has two possible values, true and false, and is used to represent the logical
values "true" and "false".

Operators of the boolean type are: not, and, or. The truth tables for these operators are:

Operators called "comparison operators" can be used to compare two integer or real values
while returning a Boolean result:

- =: is equal to;
- <: is less than;
- >: is greater than;
- <=: is less than or equal to;
- >=: is greater than or equal to;
- <>: is different from.

Example: The value of 1 <= 2 is true and the value of 10 <> 5+5 is false.

e- String type
44/ 62
We'll use strings to display a result. A character string represents a word or phrase that is not
interpreted by the machine. A character string is delimited by quotation marks, i.e. the
apostrophe character (').

A character string is an object of type string, which we'll see later.

Example: Here are some strings: 'good morning'; 'the weather's fine'; 'a sunny summer'.

Remarks:

- Since the computer reproduces character strings without interpreting them, it is possible
to write in French and use accents; however, accents are generally displayed incorrectly.
- If you want to use an apostrophe in a string, double it: 'l "oiseau'.

Example with a variable of name a and type integer:

Program var_integer;
var
a: integer; {Declaration}
Begin
a:= 5; {Assignment}
writeln(’value of a = ’, a) ; {Display : a = 5}
End.

Remarks:

- You can declare several variables of the same type at the same t ime, separating them
with commas (,).
- On declaration, variables have an indeterminate value. Variables are initialized just
after Begin (this cannot be done in the declaration).
- The declaration of a variable reserves a memory location but does not assign a default
value. As a result, variables have an indeterminate value.
In many cases, therefore, variables will have to be initialized at the start of the main
program, i.e. given an initial value.
- Variables are initialized just after Begin (this cannot be done in the declaration).
- Using the value of an uninitialized variable is a severe error!

45/ 62
- The operation "identifier:= expression;" is an assignment. We are not allowed to
write "id1:= id2 := expr;", nor "expr:= id;", nor "expr1:= expr2;" .

Example:

var a, b, c: integer;

size: real;

condition1, condition2: boolean;

3- Expression

An expression is a formula made up of constants, variables, function calls and operators. An


expression therefore has a value and a type. An expression is said to be well-formed when its
value can be calculated and its type determined. A poorly formed expression will not allow the
program to be compiled.

Example: The table below shows examples of well-formed and ill-formed expressions.

Well-formed expressions Ill-formed expressions

If an explanation is needed for the ill-formed expressions, we can say that the first attempts to
add an integer and a Boolean, the second to divide by a Boolean and the last to use the integer
div operator with a real, since sqrt(4) is indeed a real.

V- Constant

A constant is an object designated by an identifier and a fixed value. Its value is set at the
beginning of the program when it is declared. This value cannot be modified, and cannot be an
expression.

All constants used in a program must be declared, and their declarations are made after the

const keyword.

Syntax:

- 1st form: const identifier = constant_value;


- 2nd form: const identifier: type = constant_value;

46/ 62
In the first form, the type is implied if there is:

- A point (.) is a real, if not an integer;


- Odds ('), it's a character (one) or a string of characters (several).

NB: constants are always declared before variables.

Example:

Program constants ;
const
false = false;
integer = 14; {NAMED constants}
real = 0.0;
carac = ’z’;
string = ’hop’;
percent : real = 33.3; { second form with type }
Var
{variables}
Begin
{instructions}
End.

VI- Instructions

An instruction specifies an operation or sequence of operations to be performed on objects.

NB: All instructions are addressed to the computer. Each instruction must end with a semicolon
(;).

1- The assignment

Assignment is perhaps the most important instruction, since it allows you to assign a value to
a variable. This is done by replacing the previous value with the new one. The assignment
instruction is written as '':= ''.

If v is a variable of any type and expression is an expression of the same type, then the syntax
of the affection statement is: v:= expression ;

47/ 62
Example: We'll illustrate what happens when an assignment is made. Once the variable X of
type integer has been declared, it contains no value. We carry out an initial assignment,
assigning it the value 10. The variable now contains 10.

Next, we make a slightly more complicated assignment: we assign its current value plus 5. Once
this assignment has been made, X contains 15.

Before Assignment After

2- Inputs/Outputs

A program must be able to communicate with its user:

- A program can inform the user of a result or give explanations


by displaying a message;
- A program may require the user to enter values in order to function.

a- Outputs

To display a message on the screen, use the write or writeln instructions, whose syntaxes are
as follows:

- write(expression 1, ..., expression N );


- writeln(expression 1, ..., expression N);

These two instructions display the value of expressions passed as parameters. The difference
between write and writeln is that writeln goes to the line after displaying the expressions. If an
expression is a character string, the string will be reproduced on the screen. Otherwise, if the
expression is a calculation or a variable, the value is displayed.

b- Inputs

The computer can also read what the user has entered on the keyboard. To do this, it must be
asked to read what has been entered and given the variable in which the value will be stored.
To do this, we use the instructions read and readln, whose syntaxes are as follows:

- read(variable);
- readln(variable);

48/ 62
In practice, the readln instruction displays a cursor that allows the user to type text (in our case,
this can only be a real or integer number). Once the user has pressed the "enter" key on the
keyboard, the text is converted to real or integer and stored in the specified variable.

It may be useful to ask the user to enter several values at once. For this purpose, the following
two forms are equivalent:

- 1st form: readln (variable 1, ..., variable N);

- 2nd form :

readln (variable 1);

...

readln (variable 1, ..., variable N);

VII- Pratical Work (PW) No 1: Discovering the IDE environment


(Free Pascal)

1- Software installation
2- Interface presentation

The programming environment we use appears in a window at the top of which is the menu bar
(see figure below), giving access to the software's functions.

Figure: The menu bar

We're now going to take a look at the features you'll need for your practical work.

a- File menu

The File menu provides access to the following functions:

- New: opens a new editing window (in which the source code must be written).
- Open: opens an existing file.
- Save: saves the contents of the window to a file. The first time you save, you are
prompted for a file name. Subsequent saves are made to the same file.
49/ 62
- Save as: saves window contents in a new file.
- Exit: exit the software.

b- Edit menu

The Edit menu provides access to text editing functions:

- Undo: cancels the last action.

- Cut: deletes selected text and copies it to memory.

- Copy: copies selected text into memory without deleting it.

- Paste: pastes memorized text at current cursor position.

c- Run menu

In this menu, we will only use the Run option, which executes the program corresponding to
your source code. If your source code is not compiled, the Run command will execute a
compilation beforehand. However, it is preferable to run the compilation manually.

d- Compile menu

In this menu, the Compile option compiles the current source code. Compilation then creates
an executable program from the Run menu.

e- Debug menu

In this menu, the User screen option displays the program execution screen.

3- Text editor

The figure below shows a text editor window. Several windows can be open simultaneously in
the development environment.

50/ 62
Closing the file File name

Line number Column number


where cursor where cursor is
is located located

Figure: The programming environment text editor


The text editor knows the Pascal language and will change the color of words according to their
role in the code: keywords, comments and strings will be distinguished by their color.

4- Using the programming environment

Once the programming environment has been started, it is customary to create a new file
containing your source code. There can only be one program per file. Save the new file as
quickly as possible and give it a name. After that, it's a good idea to save often enough to keep
track of any changes you make to your program.

When you've finished your program, you can ask for it to be compiled; compiling requires that
you first save it. You can then run the program. The program runs in a window independent of
the programming environment. Never close it: if it doesn't close by itself, your program has a
bug.

Good practice:

To manage your files and programs, we recommend that you observe the following guidelines:

- Avoid using accents and special characters in file names: the environment doesn't
handle these characters very well;
- Give your files evocative names so that you can find them easily, and preferably a name
of the form TP1exo5 to facilitate subsequent searches;

51/ 62
- Any file name containing Pascal instructions must end with the extension ''.pas'', which
allows the environment to change the color of words according to their role;
- Save your files in your personal directory (created at the beginning of the year);
- Never open the same file several times in the same environment or several
environments: this often leads to the loss of changes made to your files.

5- The break

The pause is used to give the program a line to execute, on which it will wait for something.
You could say: "Wait for ten seconds...", but there's a simpler way, and one that programmers
prefer: wait for an input. Yes, the Enter key on your keyboard. We're going to make the program
wait, and it won't move until the Enter key is pressed. To do this, here's the line of code that
performs this action:

Read() ; or Readln() ;

This line originally says "read the character I entered", but we're going to use it to tell the
program: "Wait for the Enter key to be pressed."

This instruction must be placed after the line requesting the display of our text. Indeed, if I had
placed it before, the program would have paused before displaying the line: as I said earlier, it
executes instructions from top to bottom.

Pressing the Enter key closes the console.

6- My first program

Example: The bonjour program

A program is a sequence of instructions, some of which are key words. This program displays
the string "Bonjour" on the screen:

Program bonjour;

Begin

writeln(’Bonjour’);

End.

52/ 62
The compiler is a software program that reads (analyzes) a program and translates it into
machine code, directly executable by the computer processor.

7- Trace and output table

The trace of a program is obtained by placing writeln so that the program displays the values
of variables at runtime. This can be used to set up a program for practical work.

The output table of a program is a table with one column per variable, in which the evolution
of variables during the program run is written.

VIII- Summary table of Pascal language elements

As with algorithms, the Pascal language uses:

- Operators;
- Data structures (arrays, records);
- Control structures (repetitive, alternative);
- Functions and procedures.

Action Algorithm Pascal language

Declare variable a of type var a: Integer; var a: Integer;


Variables
integer.

const b = 10;
Constants Declare constant b. const b = 10;
const b: Integer = 10;
Assign n the value 1 n ← 1; n:= 1;
Increment variable i i ← i + 1; i:= i+1;
Assignment
decrement variable i i ← i - 1; i:= i-1;
Initialize the value of c to
c ← 100; c:= 100;
100
Write(''Hello'');
Display ''Hello''. Write(''Hello'');
Writeln(''Hello'');
Writing
Display the contents of the Write(a);
integer variable a. Write(a);
Write(a);
Reading Enter the integer a Read(a); Read(a);

53/ 62
Readln(a);
if (condition) then
Instruction;
If (condition) Then
}
Instruction block;
Simple alternative structure If (condition) then
Endif begin
Bloc d’instruction ;
End
If (condition) then If (condition) then
instruction block 1; Instruction 1;
Complete alternative
Else Else
structure
instruction block 2; Instruction 2;
Endif
If (condition 1) then If (condition1) then
instruction block 1; Instruction 1
Else If (condition 2) Else if (condition 2) then
Imbibed alternative Instruction 2
instruction block 2;
structure …
...
Conditional Else
Else
structures instruction block; Instruction;
EndIf
switch (choice) Do Case (choice) {
Case 1: instruction block C1 : bloc d’instructions 1 ;
1; C2 : bloc d’instructions 2 ;
Case 2: instruction block C3, C4 : Ic; { liste }
Choice structure
2; C5..C6 : Id; { intervalle }
Switch...Do
..... { ... }
Else other; { en option }
Otherwise: instruction
End
block n;

EndSwitch
For i from 1 to 10 Do For i:= 1 to 10 do
Complete loop (For)
instruction block; Instruction;

54/ 62
For i:= 1 to 10 do
EndFor
Begin
Iterative
Instruction block;
structures
End
while (condition) do

Instruction;
While (condition) Do
Loop with stop condition while (condition) do
instruction block;
(Tantque) Begin
EndWihle
Instruction block;
End
Repeat Repeat
Loop with stop condition
instruction block; instruction block;
(Repeat)
Until (condition); Until (condition);

Declare an array (vector)


var Tab = array[0..9] : Real ; var Tab: array [1..10] of Real;
named Tab.

Arrays Declare an array (matrix) Var T: array [1..3, 1..4] of Real;


var T=array[3][4] : Real;
named T.
Enter a value in location 2
of the table (vector) M Read(M[2]); Read(M[2]);

Display an element of index


3 of array (vector) T Write(T[3]) ; Write(T[3]);

recordName = Record Type recordName = Record


fieldname1: type1;
fieldname1: type1;
fieldname2: type2;
Create a Record data fieldname2: type2;
Recordings ...
structure ...
fieldNameN: typeN;
fieldNameN: typeN;
End recordName End;

55/ 62
Procedure procedure_name
(param1:type1, ..., paramN: Procedure procedure_name

typeN) (param1:type1, …, paramN: typeN)

Declaring variables and Declaring variables and constants


Declaring a procedure
constants Begin

Begin Instruction block;


instruction block; End;
EndProc
Functions/Pro
Function function_name
cedures Function function_name (param1:
(param1: type1, ..., paramN :
type1, …, paramN : typeN) : Type
typeN) : Type
Declaring constants and
Declaring a function Declaring constants and
variables
variables
Begin
Begin
Instruction block;
Instruction block;
nom_fonction := result;
Return(result);
End ;
EndFunc
Call a function p ← addition(x, y); p = addition(x, y);
Call a procedure addition(x, y); addition(x, y);
Addition + +
Subtraction - -
Multiplication * *
Arithmetic
Real division / /
operators
Integer division div div
Power ^ ^
Modulo (remainder of
mod mod
integer division of a by b)
Is equal to = ==
Different from <> !=
Comparison Strictly greater than > >
operators Strictly less than < <
Greater than or equal to >= >=

56/ 62
Less than or equal to <= <=
Concatenatio Concatenate the strings
n operator ''bon''+''jour'' = ''bonjour''. ''bon''+''jour'' = ''bonjour''.
''bon'' and ''jour''.

AND logic And And


Logic
operators OR logic Or Or

Logical negation No Not

Remarks:

- There is never a semicolon (;) before the else.


The else always refers to the last then encountered.

IX- Complex types

We've seen the pre-declared boolean, integer, real and char types. We'll now look at how to
create new types.

1- Creating new types

The new simple types are declared in the declarative part of the program, before being used in
the variable declaration.

Syntax:

Type type_name = type_value ;

Examples 1:

Type Name = String[20] ;

Type Entier = Integer;

Examples 2:

Program Example24 ;
Type
Chaine = String[20] ;

57/ 62
Var
Name : Chaine ;
Age : Byte ;
Begin
Write(' Enter your name: ');
ReadLn(Name);
Write('Enter your age: ');
ReadLn(Age);
WriteLn('Your name is: ',Name,' and your age: ',Age);
End.
This Example24 program uses a new type called String to declare the variable Name.

2- Interval type

Interval types are widely used. They can be of any scalar type. An interval is necessarily
ordered and continuous.

Syntax:

Type my_type = terminal_lower..terminal_upper ;

Where:

- terminal_lower and terminal_upper are constants of the same type, and are the lower
and upper bounds of the interval,
- terminal_lower <= terminal_upper

Examples:

- Type Binary = 0..1 ;


- Type Decimal=0..9 ;
- Type Alpha = 'A'...'Z' ;
- Type hundred= 1..100 ;
- Type Week=Saturday..Friday;

The instructions below apply to integer, character and enumerated interval types:

- Inc(): increments the variable passed in parameter ;


- Dec(): decrements the value of the variable passed in parameter;
- Succ(): returns the successor of the variable passed in parameter;

58/ 62
- Pred(): returns the predecessor of the variable passed in parameter;
- Ord(): returns the index of the variable in the interval to which it belongs.

Example:

Program Example31 ;
Const
Max = 100 ;
Type
Interval = 1..Max ;
Var
x : Interval ;
Begin
x := 1 ;
{...}
if not(Succ(x) = Max) then Inc(x) ;
{...}
End.

Remarks:

- The host type must be encoded as an integer (signed or unsigned, any number of bits).
The host type is then said to be an ordinal type.
- So integer, char and boolean are ordinal types.
- Only an ordinal type admits the operators pred, succ and ord (the previous, successor
and sequence number in the encoding).
- On the other hand, the real type isn't ordinal, so you can't create an interval type with
reals, as there's no notion of "consecutive reals".
- Another case of a non-ordinal type is the string type for character strings, which is not
encoded on one but on several integers. So you can't declare 'aaa'...'zzz'.

Good Practice: use named constants to bound intervals: this way, the values can be consulted
during the program, and the bounds are only written once.

Example:

Program interval ;

59/ 62
const
PMin = 0 ;
PMax = 100 ;
Var
percentage: PMin .. Pmax ;
Begin
writeln(’L’’intervalle est ’, PMin, ’ .. ’, PMax) ;
End.

3- Enumerated type

An enumerated type is a type whose associated variables will only have a very limited number
of values (a maximum of 256 different possible values). The definition of an enumerated type
consists in declaring a list of possible values associated with a type.

Syntax:

Type my_type = (val1, val2, ..., valN);

Example 1:

Type Vowel = (A, E, I, O, U);

Type Week = (Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday) ;

Example 2:

Program Example32 ;
Type
Days = (sun, mon, tue, wed, thu, fri, sat);
Var
Today: Days;
Begin
Today:= Tue ;
Today := Succ(Today) ;
Inc(Today,2) ;
case Today of
sun: Writeln('Sunday');

60/ 62
mon: Writeln('Monday');
tue: Writeln('Tuesday');
wed: Writeln('Wednesday');
thu: Writeln('Thursday');
fri: Writeln('Friday');
sat: Writeln('Saturday');
else
Writeln('autre, ',Ord(today)) ;
End ;
End.

In this Example32 program, an enumerated Days type is declared, made up of 7 elements


representing the days of the week. Note that the elements are only identifiers and have no
intrinsic value; they can only be identified by their index (the order in which they appear in the
declaration, where the first element has the number 0 and the last: n-1). First, an assignment
using the usual operator '':='' to variable Today. Then we assign its successor in the
declaration. We then increment it by 2 and, depending on its value, display the corresponding
day of the week on the screen, if possible.

Remarks:

▪ The Chr() function (specific to the Char type) does not apply to interval and enumerated
types.
▪ The Writeln() and Readln() procedures cannot be used with enumerated variables.
▪ As the enumerated type is encoded on an integer, it is an ordinal type and we can:
- Use the operators pred, succ and ord (example: pred(Orange) is Red, succ(Orange)
is Green, ord(Orange) is 1).
- Declare an interval type from an enumerated type (example: Red..Green).
▪ As the enumerated type is encoded on an integer, it is an ordinal type and we can :
- Use the operators pred, succ and ord (example: pred(Orange) is Red, succ(Orange)
is Green, ord(Orange) is 1).
- Declare an interval type from an enumerated type (example: Red..Green).

4- Structured types (records)

61/ 62
A structured type (or record) is a data structure consisting of a fixed number of components,
called fields. Unlike an array, these components are not necessarily of the same type, and are
not indexed.

The record type definition specifies for each component a field identifier, whose scope is
limited to the record, and the type of this component.

Syntax:

Type type_name = Record

field1 : type1 ; field2 :

type2 ; field3 : type3 ;

End;

NB: fields are placed in a Record...end block; and a field can itself be of type Record. In this
case, the following syntax applies:

Type type_name = Record

field1 : type1 ;

field2 = Record;

field2_1: type2;

field2_2: type3;

field2_3: type4;

End;

End;

Remarks:

- You can't display the contents of a structured variable without using a syntax specifying
the field whose value you want to know.

- The fields of a structured variable can be of any type (even arrays).

62/ 62

You might also like