Course of Algorithm and Programming
Course of Algorithm and Programming
Prerequisites:
1/ 62
Program:
I- Introduction ................................................................................................... 6
1- Definitions ................................................................................................ 6
1- Variable.................................................................................................. 10
2- Constant ................................................................................................. 11
V- Instructions ............................................................................................... 13
1- Standardized symbols........................................................................... 21
2/ 62
3- Flowchart examples .............................................................................. 23
1- Procedure ............................................................................................... 24
2- Function ................................................................................................. 25
1- Stack ....................................................................................................... 27
2- Queue ..................................................................................................... 28
3- Array ...................................................................................................... 28
4- Record .................................................................................................... 30
5- List .......................................................................................................... 31
1- Definition ............................................................................................... 33
1- Definition ............................................................................................... 34
3/ 62
2- IDE concept ........................................................................................... 38
1- Variable.................................................................................................. 41
2- Types ...................................................................................................... 41
3- Expression.............................................................................................. 46
V- Constant .................................................................................................... 46
1- The assignment...................................................................................... 47
2- Inputs/Outputs ...................................................................................... 48
4/ 62
3- Enumerated type ................................................................................... 60
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.
1- Definitions
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:
a- Definitions
A class of problems is a set of problems of the same nature or which relate to the same thing.
b- Principle
- 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.
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
7/ 62
Generally speaking, an analysis of a problem with the aim of solving it can be reduced to a
series of questions:
Whatever the type of problem you're faced with, the analysis will consist of:
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.
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.
c- Decision table
This is a tool used much more in conditional branching. It uses a table composed of two parts:
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).
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
1- Variable
A variable is an object whose value can change during the execution of the algorithm.
❖ 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;
❖ 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.
Example: Const rating = 4; Const Name = "Touza Isaac"; Const pi = 3.14; Const a=10;
11/ 62
IV- Operators
1- Types of operators
The operators used in an algorithm can be grouped into several categories including:
❖ 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.
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.
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 (;).
1- Simple instructions
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.
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);
c- Assignment instruction
It allows you to assign a value to a variable. It is used with the symbol ''←''.
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.
2- Running of an algorithm
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.
Application:
Algorithm Example
Var a, b, c, s: Integer;
Begin
Read(a);
Read(b);
Read(c);
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.
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:
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
Else
EndIf
Remarks:
If (condition 1) then
Instruction blocks 1;
Instruction blocks 2;
…..
17/ 62
Else
Instruction block n;
EndIf
This is a conditional structure used to select a block of instructions to be executed from several
choices at once.
Syntax:
Switch (selector) Do
…..
Endswitch
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.
The instructions are repeated a certain number of times. The repetition may or may not be
known.
18/ 62
A cycle is a turn of the loop. There are two types of loops:
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:
Instruction blocks;
EndFor
With:
Example:
For i from 1 to 10 Do
Write(''give a number'');
EndFor
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
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
hour ←hour+1;
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.
1- Standardized symbols
21/ 62
2- Rules for constructing algorithms
22/ 62
3- Flowchart examples
Begin
Algorithm Somme
Var Real ;
Real ; Read(a,b)
Begin
Write (’’enter the first number’’);
Read(b); S←a+b
Write(s);
End End
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
1- 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.
Declaration of constants;
Declaration of variable;
Begin
/*Procedure body*/
EndProc
b- Calling a procedure
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.
Example:
Var s: Real;
Begin
s ← a + b;
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
Declaration of constants;
Declaration of variable;
Begin
/*Function body*/
Return (variableName);
EndFunc
25/ 62
b- Calling a function
Example:
Var s: Real;
Begin
S←a+b;
Return s ;
EndFunc
0 𝑖𝑓 𝑛 < 1
𝑓(𝑛) = {
𝑓(𝑛 − 1) + 2 𝑒𝑙𝑠𝑒
Begin
If 𝑛 < 1 then
Return 0;
Else
Return (Recc(n-1)+2);
EndIf
EndFunc
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.
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.
2- Queue
A Queue is a data structure in which data is stored in FIFO (First In First Out) order.
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.
Remarks:
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
ou
Example: Declare a table named “Tab” allowing you to store the ages of 10 babies in a
maternity ward.
b- Multi-dimensional array
Also called a matrix, it is an array in which access to an element is done using several indices.
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 (𝑥, 𝑦).
29/ 62
Example: Write(Note[9]); Write(Note[6]); Write(T[0][0]);
4- Record
nameRecord = Record
fieldname1: type1;
fieldName2: type2;
fieldNameN: typeN;
End nameRecord
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.
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:
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.
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
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.
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
- (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.
- 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.
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;
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
The notions of algorithm and program are related, but should not be confused.
A compiler is an application that transforms the source code of a program into a machine-
executable binary file.
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.
Delphi, javac, GCJ (Gnu Compiler for Java), Jikes, Visual Basic, FreeBasic. To
2- IDE concept
38/ 62
It consists of:
Some examples of IDEs: Code::Blocks, Visual Studio, Qt Creator, Dev C++, Dev Pascal,
Eclipse ; Android Studio ; Dr Java ; My Eclipse ; J Developer...
The code below shows the general structure of a program written in Pascal:
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 (.).
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.
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.
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).
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.
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.
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
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.
- 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.
Remarks:
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 (').
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'.
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;
3- Expression
Example: The table below shows examples of well-formed and 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:
46/ 62
In the first form, the type is implied if there is:
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
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.
2- Inputs/Outputs
a- Outputs
To display a message on the screen, use the write or writeln instructions, whose syntaxes are
as follows:
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:
- 2nd form :
...
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.
We're now going to take a look at the features you'll need for your practical work.
a- File menu
- 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
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
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.
6- My first 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.
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.
- Operators;
- Data structures (arrays, records);
- Control structures (repetitive, alternative);
- Functions and procedures.
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);
55/ 62
Procedure procedure_name
(param1:type1, ..., paramN: Procedure procedure_name
56/ 62
Less than or equal to <= <=
Concatenatio Concatenate the strings
n operator ''bon''+''jour'' = ''bonjour''. ''bon''+''jour'' = ''bonjour''.
''bon'' and ''jour''.
Remarks:
We've seen the pre-declared boolean, integer, real and char types. We'll now look at how to
create new types.
The new simple types are declared in the declarative part of the program, before being used in
the variable declaration.
Syntax:
Examples 1:
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:
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:
The instructions below apply to integer, character and enumerated interval types:
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:
Example 1:
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.
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).
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:
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:
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.
62/ 62