Text Book
Text Book
Faculty of Technology
Computer Science Department
Text Book
2024 / 2025
Table of Contents
2
3. Flowchart with conditional statement ...................................................................................... 24
4. Conditional statements in C programs ...................................................................................... 24
4.1. If expression....................................................................................................................... 25
4.2. If / else statement.............................................................................................................. 25
4.3. Switch ................................................................................................................................ 26
Chapter 4 : Loops................................................................................................................................... 28
1. Introduction ............................................................................................................................... 28
2. For loop...................................................................................................................................... 28
3. While loop ................................................................................................................................. 29
4. Repeat loop ............................................................................................................................... 29
5. Table of loops execution ............................................................................................................ 30
6. Infinite loops .............................................................................................................................. 31
7. Nested loops .............................................................................................................................. 31
8. Loops in C programs .................................................................................................................. 32
8.1. For loop.............................................................................................................................. 32
8.2. While loop ......................................................................................................................... 32
8.3. Do .. while loop .................................................................................................................. 33
Chapter 5 : Array Structure ................................................................................................................... 35
1. Introduction ............................................................................................................................... 35
2. The Arrays .................................................................................................................................. 35
2.1. Creating arrays ................................................................................................................... 35
2.2. Accessing Array Elements .................................................................................................. 36
2.3. Array algorithms ................................................................................................................ 37
2.4. Shift array........................................................................................................................... 39
3. Sorting Arrays ............................................................................................................................ 39
3.1. Selection sort ..................................................................................................................... 40
3.2. Bubble Sort ........................................................................................................................ 40
3.3. Insertion Sort ..................................................................................................................... 42
4. 2-Dimensional arrays (matrices)................................................................................................ 42
4.1. Accessing elements of a matrix ......................................................................................... 43
4.2. Operations on matrixes ..................................................................................................... 43
4.3. Arrays in C programs.......................................................................................................... 44
Chapter 5 : Enumerations and Structures ............................................................................................. 47
1. Enumerations ............................................................................................................................ 47
1.1. Enumerations .................................................................................................................... 47
1.2. Enumerations in C.............................................................................................................. 47
3
2. Structures .................................................................................................................................. 48
2.1. Declaration of Records/Structures .................................................................................... 48
2.2. Accessing the fields of a structure ..................................................................................... 49
2.3. Array of structures ............................................................................................................. 49
2.4. Operations on structures ................................................................................................... 49
2.5. Structures in C ................................................................................................................... 51
4
Chapter 2 : Sequential Algorithms
1. Algorithm vs Program
An algorithm is the precise description of the method of solving a problem in the form of simple
instructions. The algorithm is characterized by:
• Identification of information involved in a program
• Abstraction: modeling, formalization and representation of this information
• List of operations to be applied to this information.
• Definition of the order of operations to be respected.
2. Algorithm Components
An algorithm consists of three main parts:
• The header: this part is used to give a name to the algorithm. It is preceded by the word
Algorithm;
• The declarative part: in this part, we declare the different elements that the algorithm
uses (constants, variables, structures, procedures and functions.);
• The body of the algorithm: this part contains the instructions of the algorithm. It is
delimited by the words “Begin” and “end”.
Variables can store digits, numbers, characters, character strings, etc. whose value can be
modified during the execution of the algorithm. Variables are introduced by the keyword “Var”
as:
5
Var name_identifier : type ;
Constants as well as variables are designed by identifiers. Herein, an identifier is a name that
follows a particular syntax:
The rules for identifiers vary slightly depending on the specific programming language, but
here are some general guidelines that apply to most languages:
• Identifiers must consist of letters (both uppercase and lowercase), digits (0-9), and
underscores (_).
• The first character must be a letter or an underscore.
• Identifiers cannot contain spaces or other special characters.
• Identifiers can be of varying lengths, but there may be limitations imposed by the
specific language or implementation.
• Some languages may have a maximum length for identifiers.
• Identifiers cannot be the same as reserved keywords in the language. Keywords have
special meanings and cannot be used as variable or function names.
• Some languages are case-sensitive, meaning that “variable” and “Variable” are
considered different identifiers.
• Other languages are case-insensitive, meaning that both variable and Variable would
refer to the same identifier.
• It is generally recommended to choose identifiers that are meaningful and descriptive,
making your code easier to understand and maintain.
Here are some examples of valid and invalid identifiers in most programming languages:
Valid identifiers:
• number
• my_number
• Number123
• _private_number
Invalid identifiers:
• 123variable (starts with a digit)
• variable with space (contains a space)
• $variable (contains a special character)
• if (a reserved keyword)
By following these rules and guidelines, you can ensure that your identifiers are valid and
meaningful.
6
4. Standard primitive types
The type corresponds to the kind of information used. Standard primitive types are those types
that are available on most computers as built-in features.
The standard types in algorithmic languages include the whole numbers, the logical truth
values, and a set of printable characters. We denote these types by the identifiers INTEGER,
REAL, BOOLEAN, CHAR, and STRING (of characters). Each type has a set of operations.
The standard operators for integers are the four basic arithmetic operations of addition (+),
subtraction (-), multiplication (*) and division (/, DIV).
7
For example, if x has for value 3, and y is 4, the expression “x=y” would be evaluated as FALSE.
The character set defined by the International Standards Organization (ISO), and particularly
its American version ASCII (American Standard Code for Information Interchange) is the most
widely accepted set. The figure below shows the ASCII table with all 256 characters. They are
numbered from 0 to 255. Each character is stored in computer memory on one byte.
To determine the rank (the order) of a character ('A' for example) in the set of characters
represented by this table, one must add the two numbers found on the same line (in the first
column on the left) and the same column (in the first row at the top). Example: The rank of the
character 'A' is equal to 64 + 1 = 65.
A character type constant is represented by one and only one character framed by two quotes.
Examples: ',a', 'b', 'C', '!', '#', …
The operations defined by functions on the Character type are:
8
ORD( c ): This function returns a positive integer corresponding to the rank of the character c,
in all the characters.
Examples: Ord('!') = 33, Ord ('A') = 65, Ord ('a') =97.
CHR(i): is the inverse function of Ord. For a positive integer i, it returns the character of rank
i.
Examples: Chr(33) = '!', Chr(65) = 'A', Chr(97) = 'a'.
SUCC( c ): provides the character that immediately follows the character c in all the characters.
Examples: Succ('a') = 'b', Succ('3') = '4', Succ('%') = '&'.
PRED( c ): provides the character immediately preceding the character c in all characters. This
is the inverse function of Succ.
Examples: Pred('b') = 'a', Pred ('4') = '3', Pred ('&') = '%'
In summary, each type has a particular size and representation in computer memory. The
different forms of constants should not be confused.
Examples: 3 (integer type), 3.0 (real type), '3' (character type) and "3" (string type).
5. Basic operations
An expression is a series of operations applied to a set of factors (arguments or parameters).
Each expression has a value and a type.
If an expression contains several operators with the same priority, these operators are left
associative.
Example:
9
The expression: X + Y * Z , leads to the evaluation of X + (Y * Z).
In case, one wish to modify the semantic induced by this rule, parenthesis have to be used.
Note that comparisons are operations yielding a result of type BOOLEAN. Thus, the result of
a comparison may be assigned to a variable, or it may be used as an operand of a logical operator
in a Boolean expression.
For instance, given Boolean variables p and q and integer variables x = 5, y = 8, z = 10,
the two assignments:
p is x = y, and q is (x ≤ y) AND (y < z)
yield p = FALSE and q = TRUE.
Comparison operators are: <, >, =, ≠, ≤, ≥
6. Basic instructions
10
In algorithmics, there are three elementary instructions: Read, Write and assignment ( ). Each
instruction is followed by a semicolon (;)to specify its ending.
Several successive writing instructions can be grouped into a single instruction. For example,
the sequence of instructions:
Example :
Write (“The result is =" ); Write (X);
11
Can be replaced by:
Write (“The result is =”, X);
This instruction displays the string "Result is =10.”
This statement specifies that the variableName receives the value of expression.
Examples: X 7 ; // Assign a constant value to the variable X (X receives 7).
Y X ; // Copy the value of variable X into variable Y (Y receives X).
Z 2 * X + T / Y // Z receives 2 * X + T / Y.
Remarks:
• If the variable already contained a value, it would be replaced by the value of the
expression. The old value of the variable is lost and there is no way to recover it.
• A type check operation is performed before assignment. It is an error if the value of the
expression does not belong to the type of the variable, unless it is a value integer and
that the variable is of real type. In this case the integer value is converted to real.
Example :
Algorithm Permutation ;
Var X, Y, Z : integer ;
Begin
Read( X, Y ) ;
ZX;
XY;
YZ;
Write (X, Y) ;
End.
12
If the read values of X and Y are 17 and 10 respectively, what would be the outputted values.
7. Examples of algorithms
Example 1: The following algorithm displays a hello message.
Algorithm hello_v1;
Begin
Write ("Hello world");
End.
Example 2 :
Algorithm hello_v2;
Var name : string ;
Begin
Write ("Please, enter your name ");
Read(name);
Write("hello ", name);
End.
Example 3: The following algorithm computes and displays the surface of a rectangle
Algorithm surface_r;
Var length, width, surface : integer ;
Begin
Write ("Enter the rectangle length: ");
Read(length);
Write ("Enter the rectangle width: ");
Read(width);
surface length * width ;
Write(“The surface is : ", surface);
End.
Example 4: The following algorithm computes and displays the perimeter of a circle
Algorithm perimeter_c;
Const pi = 3.14;
Var radius : integer ;
13
perimeter : real;
Begin
Write ("Enter the circle radius: ");
Read(radius);
surface 2 * pi * radius ;
Write(“The perimeter is : ", surface);
End.
8. Flow chart
A flowchart is a diagrammatic representation of algorithm to plan the solution to the problem.
Constructed by using special geometrical symbols where each symbol represents an activity.
The activity would be input/output of data, computation/processing of data etc.
8.1. Flowchart symbols
Symbol Meaning
Begin / End
Operations, instructions, …
Input / Output
Relationship
Decision
8.2. Example
Example of a flowchart that calculate the sum of two numbers.
Begin
Read A, B
SA+B
Write S
End
14
9. The language C
C is a general-purpose, that has been around since the early 1970s. It's renowned for its
efficiency, portability, and flexibility, making it a cornerstone of software development.
The C programming language is considered a mid-level language, though it's often
described as leaning more towards a low-level language due to its close interaction with
hardware. Indeed, C provides direct manipulation of memory through pointers, bitwise
operations, and access to system-level functions. This allows for writing programs that operate
very close to the machine's hardware, similar to assembly language. C also has features of high-
level languages, such as structured programming, functions, and abstractions like data types
(e.g., arrays, structs), making it more accessible than true low-level languages like assembly.
9.1.1. Documentation
Documentation consists of the description of the program, programmer's name, and creation
date. These are generally written in the form of comments.
In a C program, single-line comments can be written using two forward slashes i.e., //, and we
can create multi-line comments using /* */.
Example:
// This is my first program /*
I am 1st year Bachelor student */
Both methods work as the document section in a program. It provides an overview of the
program. Anything written inside will be considered a part of the documentation section and
will not interfere with the specified code.
15
Example :
#include <stdio.h>
#include <math.h>
There are various header files available for different purposes. Here are some examples of
header files in C:
• stdio.h: This header file contains declarations for standard input and output functions,
such as printf(), scanf(), and fopen().
• stdlib.h: This header file contains declarations for general utility functions, such as
malloc(), free(), and rand().
• math.h: This header file contains declarations for mathematical functions, such as
sin(), cos(), and log().
• string.h: This header file contains declarations for string manipulation functions, such
as strcpy(), strcat(), and strlen().
• time.h: This header file contains declarations for time and date functions, such as
time() and strftime().
In addition to these standard header files, there are also many user-defined header files that are
available. For example, a header file for a linked list data structure might contain declarations
for the struct node type and functions for creating, inserting, and deleting nodes in the linked
list.
9.1.3. Definition
A preprocessor directive in C is any statement that begins with the "#" symbol. In particular,
the “#define” is a preprocessor compiler directive used to create constants, ie, “#define”
basically allows the macro definition, which allows the use of constants in our code.
Example :
#define PI 3.14159265358979323846
“#define” allows us to use constants in our code. It replaces all the constants with its value in
the code.
Global variables and functions can be very useful, but they should be used with caution. If you
use too many global variables and functions, your program can become difficult to maintain
and debug. It is generally better to use local variables and functions whenever possible.
17
To execute a C program, one should follow these steps:
1. Compile the C program using a C compiler. The C compiler will convert the C source
code into machine code that the computer can understand.
2. Link the compiled C program with any necessary libraries. Libraries are collections of
pre-compiled code that can be used by C programs.
3. Execute the linked C program.
The execution of this program will produce the following display on the screen:
In addition to these basic data types, C also has a number of compiler-specific data types, such
as long and short.
Example : // Basic data types
int my_integer_variable = 10;
float my_floating_point_variable = 3.141592653589793;
18
char my_character_variable = 'a';
void my_void_function() {
19
Besides these types, in C, Boolean is a data type that contains two types of values, i.e., 0 and 1.
Basically, the bool type value represents two types of behavior, either true or false. Here, '0'
represents false value, while '1' represents true value.
We can also assign the value of one variable to another variable. Generally, the value is issued
from an expression.
An expression in C is a combination of operands and operators. Operands are the values
that are operated on, and operators are the symbols that perform the operations. Expressions
can be used to evaluate mathematical expressions, compare values, and perform other logical
operations. Here are some additional tips for using assignment in C:
• Only assign values to variables of the correct data type.
• Be careful not to overwrite the value of an important variable.
• Use parentheses to make your code more readable and to avoid errors. There are many
operators in C, in particular, we mention:
o Arithmetic Operators
o Relational Operators
o Logical Operators
20
9.4.2. scanf() function
The scanf() function reads formatted input from the standard input (usually the keyboard). It
takes a format string and a list of variables, similar to printf().
21
Chapter 3: Control Statements
Control statement structures require that the programmer specifies one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed if
the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Conditional statements in algorithms allow the algorithm to make decisions based on the
value of a Boolean expression. This means that the algorithm can choose different paths of
execution depending on whether the condition is true or false.
Conditional statements are one of the most important building blocks of algorithms, and
they are used in a wide range of applications, including sorting, searching, and graph
algorithms.
The condition is a Boolean expression, which the evaluation leads to either True or False. The
codition is mainly defined using relational operators: =, ≠, >, <, ≥, and ≤ . The simple expression
resulting on the use of these operators may be combined using logic operators: AND, OR, and
NOT.
Example:
If (A <> 0) Then
D =X /A;
endIf ;
Example 1:
If (number > = 0) Then
Write(“The number is positive”)
Else
Write(“The number is negative”)
endIf;
Example 2:
If (age >= 18 AND hasDriversLicense = TRUE) Then
write("You are eligible to rent a car.")
Else
write("You are not eligible to rent a car.")
endIf ;
Example:
23
2. Multiple choice selection
When multiple choices are available, the use of an appropriate structure is suitable. Herein, a
conditional control structure is used when the processing depends on the value that a selector
will take. This selector is of integer, character or boolean type.
Syntax :
case (selector) of
choice1: instructions1
choice2: instruction2
…
Default : instructionsN
endCaseOf ;
24
4.1. If expression
if (expression){
//code to be executed
}
The logical operators in C language are logical AND ( && ), logical OR ( || ), and logical NOT
( ! ).
if (expression){
//code to be executed if condition is true
} else {
//code to be executed if condition is false
}
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario
where there are multiple cases to be performed for different conditions.
if(condition1){
//code to be executed if condition1 is true
}else if (condition2){
//code to be executed if condition2 is true
}
else if (condition3){
//code to be executed if condition3 is true
25
}
...
else {
//code to be executed if all the conditions are false
}
Example 1:
4.3. Switch
The switch statement allows to select one of many code blocks to be executed. It is useful when
there are multiple cases to consider. The syntax in C is as follows:
switch (expression){
case x:
//code block
break;
case y:
// code block
break;
default:
// code block
}
26
• The default statement is optional, and specifies some code to run if there is no case
match
Example: The following program translates a grade into an assessment.
27
Chapter 4 : Loops
1. Introduction
Sometimes, we repeat a specific code instruction multiple times to solve a problem until a
specific condition is met. This is known as iterations, which allows us to write code once and
execute it multiple times.
There are mainly three types of loops: For, While, and Repeat. Usually, Loops have
three main elements which are:
Initialization: we assign an initial value to a variable used when evaluating the loop condition.
The loop condition: is a Boolean expression often evaluated before the execution of the loop
body as in the case of while and for loops, and after the execution of the loop body as in the
case of repeat. In any case, the body of the loop is running until the condition will be evaluated
as false.
Variation of the loop condition: this is usually done at the end of the loop body as an increment
or decrement of a counter used to evaluate the loop condition as in the case of while, repeat.
Forgetting or incorrectly performing this step causes the loop body to execute infinitely, or give
unexpected results.
2. For loop
For loops are used when you know how many times you want to repeat a certain block of code.
This is known as definite iteration. A for loop uses a counter to tell it how many times to run
the same sequence of activities.
The counter has the following three numeric values:
• Initial counter value
• Increment (the amount to add to the counter each time the loop runs)
• Final counter value
The loop ends when the counter reaches the final counter value.
Syntax Flowchart
For ctr = initial_value To final_value
Begin
statements
End
endFor
28
Example: Display the five first number
Algorithm countV1;
var i:integer;
Begin
for i 10 to 20 do
Begin
Write(i);
End;
End.
3. While loop
While loop is used to execute the body of the loop until a specific condition is false. We apply
this loop when we don't know how many times it will run.
The while loop consists of a loop condition, a code block as loop body and a loop update
expression. First, the loop condition is evaluated, and if true, the code in the body of the loop
will be executed. This process repeats until the loop condition becomes false.
Syntax Flowchart
Initialization of the loop
While (condition of the loop) do
Begin
Loop’s body
Condition update
End;
Example:
Algorithm countV2;
var i: integer;
Begin
i 10; //initialization
While(i<=20) DO //the number 20 is included
Begin
Write(i);
i i+1; //we increment the counter i
End;
End.
4. Repeat loop
Repeat loops are used when it is once again indefinite iteration. This means that while we do
not know how many times to loop something, we can just use a Repeat loop.
29
The loop repeat-until executes a block of instructions repeatedly, until a given condition
becomes true. The condition will be re-evaluated at the end of each iteration of the loop.
Because the condition is evaluated at the end of each iteration, a repeat/until loop will always
execute at least once.
Syntax Flowchart
Initialization of the loop
repeat
Begin
Loop’s body
Condition update
end;
Until(condition)
Example:
Algorithm countV3;
var I : integer;
Begin
i 20;//initialization
repeat
Begin
write(i);
i i-1; // variation of the condition
End;
until (i<10) //the number 10 is included
End.
30
write(sum+ " ");
i i+1;
End;
End.
6. Infinite loops
The problem of infinite loops occurs when there is an error in the condition of the loop, or in
the variation of the condition, below are the possible causes of an infinite loop:
• The counter is not varied (incremented or decremented), this is not the case of the loop
for because the variation of the counter is done automatically.
• Vary the loop counter so as to never check the stopping condition, in this case, it is
necessary to clearly specify the range of the counter, its limits, and the movement of the
counter (increment or decrement).
• Vary the loop counter inside a conditional statement.
• Wrong condition.
To avoid the infinite loop problem, you must take the following precautions:
• Carefully study the range of variation of the counter.
• Specify the loop condition carefully by taking into account the extreme values of the
counter.
• Involve the counter in the loop condition and don't forget to vary it.
7. Nested loops
A nested loop means a loop inside another loop. We can have any number of loops inside
another loop.
Example:
For i 0 to 10 do
for j 0 to 5 do
statements;
31
8. Loops in C programs
8.1. For loop
Syntax
for (i=initial value; condition; variation of i)
{
Loop’s body
}
Example :
The result is
8.2.While loop
Syntax:
Initialization of the loop
while(condition of the loop)
{
Loop’s body
Condition update
}
32
Example
Example:
33
The result is:
34
Chapter 5 : Array Structure
1. Introduction
An array is a data structure that consists of a set of values from the same data type with a single
identifier name. Elements are stored at contiguous memory locations.
Array identifier 10 5 7 12 0 5
0 1 2 3 4 5
Array indexes
2. The Arrays
2.1. Creating arrays
Syntax for declaring an array:
Many options are possible to declare an array:
1st option
var array_name : array[0.. number_of_values_to_hold-1] of data_type;
2nd option
var array_name : array[number_of_values_to_hold] of data_type;
3nd option
Type name_of_type : array[0..numberOfValuesToHold-1] of data_type;
Var array_name : name_of_type ;
35
Example :
const numDays = 7 ; N = 5 ;
type numArr : array[0..4] of int ;
Example :
daysOfWeek = [“sunday”, “monday”,”tuesday”,”wednesday”,”thuesday”,”friday,”saturday”]
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’] ;
scores = [12, 8, 14, 9, 10] ;
Example:
myDay = daysOfWeek[1] ;
for i = 0 to N-1
write(T[i])
endFor
36
or (the reverse order)
for i= (N-1) to 0
write(T[i])
endFor
2.3.1. Find the maximum and minimum element in an array (and their indexes)
algorithm max_min_tab;
const N=10;
var tab : array[0..N-1] of integer ;
i, max, min, indexMin, indexMax : integer;
Begin
min tab[0] ;
max tab[0] ;
indiceMin 0 ;
indiceMax 0 ;
for i 0 to (N-1) do
Begin
if (min > tab[i])
then begin
min tab[i] ;
indiceMin i;
end;
endIf
37
if (max < tab[i])
then begin
max tab[i] ;
indiceMax i;
end;
endIf
endFor
writeln("le min =", min, " at the index : ", indexMin) ;
writeln("le max =", max, " at the index : ", indexMax) ;
End.
2.3.2. Find the sum and the product of all elements in an array
algorithm sum_product_tab;
const N=10 ;
var tab : array [0..N-1] of integer;
i, sum, product : integer;
begin
sum 0 ;
product 1 ;
for i 0 to (N-1) do
begin
sum sum + tab[i] ;
product product * tab[i];
end ;
endFor
writeln(“The sum is” : , sum) ;
writeln(“The product is” : , product) ;
end.
found false ;
i0;
while ((found = false) and (i<N)) do
begin
if tab[i] = x then begin found true ;
endIf ;
i i+1 ;
end;
endWhile
38
• Binary search is a more efficient algorithm that can be used on sorted arrays. It works
by repeatedly dividing the array in half and comparing the middle element to the target
element. If the target element is equal to the middle element, the algorithm returns its
index. Otherwise, the algorithm recursively searches the half of the array that contains
the target element.
3. Sorting Arrays
Sorting is one of the basic operations on the arrays. Indeed; it’s usually helpful when we have
an array to be able to put it in some sort of order (be it numerical or alphabetical).
There are many algorithms to sort a list. Some are simple and some are complex. Some are fast
while others are slow.
39
3.1. Selection sort
Selection sort is a simple sorting algorithm that works by repeatedly finding the smallest
element in an unsorted array and swapping it with the first element in the array. This process is
repeated until the entire array is sorted.
for i 0 to (N – 1-1) do
Begin
smallest = i ;
for j (i + 1) to N-1 do
if array[j] < array[smallest] then smallest = j
endFor ;
temp array[i]
array[i] array[j]
array[j] temp
end
endFor
for i 0 to n-1-1 do
begin
for j 0 to n-i-1 do
40
if (tab[j]>tab[j+1])
then begin
tmp tab[j];
tab[j] tab[j+1];
tab[j+1] tmp;
end;
endIf;
endFor ;
end ;
endFor.
Illustration
Array to sort : 8 4 2 5 3 7
Pass 1
Compare 8 and 4: Swap
Array: 4 8 2 5 3 7
Compare 8 and 2: Swap
Array: 4 2 8 5 3 7
Compare 8 and 5: Swap
Array: 4 2 5 8 3 7
Compare 8 and 3: Swap
Array: 4 2 5 3 8 7
Compare 8 and 7: swap
Array: 4 2 5 3 7 8
Pass 2
Compare 4 and 2: Swap
Array: 2 4 5 3 7 8
Compare 4 and 5: No swap required
Array: 2 4 5 3 7 8
Compare 4 and 3: Swap
Array: 2 3 4 5 7 8
Compare 4 and 7: No swap required
Array: 2 3 4 5 7 8
Compare 4 and 8: No swap required
Array: 2 3 4 5 7 8
41
Pass 3
Compare 2 and 3: No swap required
Array: 2 3 4 5 7 8
Compare 2 and 4: No swap required
Array: 2 3 4 5 7 8
Compare 2 and 5: No swap required
Array: 2 3 4 5 7 8
Compare 2 and 7: No swap required
Array: 2 3 4 5 7 8
Compare 2 and 8: No swap required
Array: 2 3 4 5 7 8
for i 1 to N-1 do
temp array[i] ;
ji–1;
while j >= 0 and array[j] > temp do
begin
array[j + 1] array[j] ;
jj–1;
end ;
array[j + 1] temp ;
42
Syntax of declaration:
array_name : array[0 ..numberOfRows-1][0 ..numberOfColumns-1] of data_type;
Begin
for i 0 to (n -1) do
for j 0 to (m-1) do mat[i][j] 0;
endFor;
endFor;
End.
Algorithm sum_mat ;
const n=4, m=5;
var mat : array[0 ..n-1][0 ..m-1] of integer ;
i, j, sum : integer ;
Begin
for i 0 to (n -1) do
begin
sum 0 ;
for j 0 to (m-1) do sum sum + mat[i][j] ;
endFor;
writeln(sum);
end;
endFor;
End.
43
Algorithm sum_2_mat ;
const n=4, m=5 ;
type matrice : array [0 ..n-1][0 ..m-1] of integer ;
var mat1, mat2, mat3 : matrice ;
i, j : integer;
Begin
for i 0 to (n -1) do
for j 0 to (m-1) do
mat3[i][j] mat1[i][j] + mat2[i][j] ;
endFor;
endFor;
End.
algorithm product_mat;
const n=4,m=5,p=6;
var mat1 : array[0.. n-1][0 ..m-1] of integer ;
mat2 : array[0 ..m-1][0 ..p-1] of integer ;
mat3 : array[0.. n-1][0 ..p-1] of integer ;
i, j, k, sum : integer ; // the variable sum is used to compute the product between vectors
Begin
for k 0 to (n -1) do
for i 0 to (p -1) do
begin
sum 0;
for j 0 to (m-1) do sum sum+(mat1[k][j]*mat2[j][i]);
endFor ;
mat3[k][i] sum;
end ;
endFor;
endFor ;
End.
44
4.3.1. Searching for an element in an array
4.3.2. Sorting
The following program performs the sorting according to the selection sort algorithm. This
program works by iterating over the array and finding the smallest element in the unsorted part
of the array. It then swaps the smallest element with the current element. The program repeats
this process until the entire array is sorted.
45
4.3.3. Operations on Matrices
46
Chapter 5 : Enumerations and Structures
1. Enumerations
1.1. Enumerations
The set type is created by defining the domain of values it contains, i.e., the list of constant
values that variables of this type can take. Variables of this type take a value among a set.
Syntax for declaration
type enum_type = set(value1, value2, …);
Example :
type color= set (blue, green, red);
var c1 : color;
c1 green;
Enumerations are especially useful for enhancing code readability making the code more
understandable and maintainable. The sets can be used to iterate in loops like
type Color= set (blue, green, red, white);
var c1:color;
for c1 blue to white do write (c1);
1.2. Enumerations in C
In C language, an enumeration is declared using the 'enum' keyword.
Syntax:
enum enum_type {value1, value2, …};
Example:
enum color {white, blue, yellow, green, black};
We declare a variable of type 'color' by specifying the name of the enum followed by the name
of the variable to be declared, for example: enum color c1;.
Additionally, we can assign numerical constants to each color as follows:
enum color {white=10, blue=11, yellow=12, green=13, black=14};
47
If numerical constants are not specified, these values start from 0 and increment by 1 for each
subsequent enumerator.
2. Structures
Unlike arrays, which are data structures where all elements are of the same type,
records/structures are data structures where the elements can be of different types and relate to
the same semantic entity.
• The elements that compose a record are called fields or attributes.
• A record is a user-defined data type that allows grouping a finite number of elements of
different types.
• A record is a complex variable that allows designating, under a single name, a set of
values that can be of different types (simple or complex).
• Before declaring a record variable, it's necessary to have previously defined the name
and type of the fields that compose it.
• It's possible to create custom types and then declare variables or arrays of elements of
that type
Where <id1>, <id2>, ..., <idN> are the identifiers of the fields, and <type1>, <type2>, ...,
<typeN> are their types respectively.
Example :
type car = structure
brand: string;
price: float;
end;
var v1 : car;
48
2.2. Accessing the fields of a structure
To access a field of a structure, the variable ID of the structure type is used, followed by a dot
and then the name of the field you want to access.
Syntax:
<structVariable>.<fieldName>
For example, to access the 'price' field of the variable 'v1' of type 'car',
v1.price
Assignment: v1.price ← 2000.00;
Or:
floatVariable ← v1.price;
Reading: read(v1.price);
49
c: string;
price: float;
end;
In the following are instructions to display the content of the aforementioned array.
for I 0 to (n -1) do begin
write(listCar[i]. brand);
write (listCar[i].c);
write(listCar[i]. price); endFor;
end;
In the following, instructions to sort elements of listCar array according to the price (bubble
sort)
var tmp : car;
i, j : integer;
…
for i (n-2) to 0 do begin
for j 0 to i do
if (listCar[j].price > listCar[j+1].price) then begin
tmp listCar[j];
listCar[j] listCar[j+1];
listCar[j+1] tmp;
end; endIF;
endFor;
endFor;
50
2.5. Structures in C
To use structure in our program, we have to define its instance. We can do that by creating
variables of the structure type. We can define structure variables using two methods:
• Variable declaration with structure declaration:
struct structureName {
type1 id1;
type2 id2;
....
....
}var1, var2, ...;
Members of a structure are accessed with a dot after the structure identifier.
Example in C
In the following is a C program that creates a list of three cars, and display them according to
their year.
51
52