Saad Dahlab University - Blida1
Faculty of Sciences
Department of Computer Science
Computer Science Engineering
Semester 1 (1st year)
CHAPTER III: ARRAYS
Mrs AROUSSI (s_aroussi@[Link])
2024-2025
Available at [Link]
de-donn%C3%A9es
CONTENT
Introduction
Definitions
Vectors.
Strings
Matrixes
2
INTRODUCTION
Some situations cannot be treated with simple variables only. They can only
keep one value at a time.
Using multiple data multiple times can be tricky in a program.
Example: Rank the students in the group (30 students!) according to their
average use 30 real variables!!
Var M1 , M2 ,M3 ,M4 ,M5 ,M6 ,M7 ,M8 ,M9 ,M10 ,M11 ,M12 ,M13 ,.....: real
Arrays: allow to regroup the averages into a structure.
3
M1 M2 M3 M4 M5 M6 M7 M8 M9 M10 M11 M12 … … M30
DEFINITIONS
Arrays are structured variables, consisting of a fixed number (static) of
elements (items), all of the same type, and accessible using indexes. They
are characterized by their dimension:
Dimension Appellation
1 One-dimensional array or Vector
2 Two-Dimensional array or Matrix
3 Three-dimensional array or Cube
N>3 multidimensional array
0 1 2 3 4 5 6 2
1
0 0
Vector 1 0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1
2 Matrix Cube
3 2 4
4 3
5 0 1 2 3 4 5
DEFINITIONS
To define an array, you should specifiy:
its dimension
the maximum number of its elements in each dimension (i.e. d), i.e. its
maximum size in each dimension (i.e. Smaxdimension)
the type of each element (typelt)
its name (identificator)
The declaration is made by specifying the word ARRAY, followed by the size
in square brackets of each dimension followed by the word OF and the type of
elements.
identifier: ARRAY [Smax1] [[Smax2]…. [Smaxd]] OF typelt 5
The number of brackets [ ] designates the dimension (d) of the array.
DEFINITIONS
Example:
Dimension Algorithmic Language (AL) C Language (CL)
1: Vector VAR V: array [100] of integer int V [100];
2: Matrix VAR M: array [100][200] of integer int M [100][200];
3: Cube VAR C: array [100][200][300] of integer int C [100][200][300];
V is a vector of 100 elements,
M is a matrix of 100 rows and 200 columns (each row is a vector)
C is a cube of 100 layers where each layer has 200 rows and 300 columns
(each layer is a matrix).
6
DEFINITIONS
There are other methods of declaring the array:
Method No Algorithmic language C language
1: declare as much VAR A: array [100] of integer int A [100];
as variable
2: use a constant CONST Smax = 100 const int Smax = 100;
to declare the VAR A: array [Smax] of integer int A [Smax];
maximum size
(Smax)
3: declare as much CONST Smax = 100 const int Smax = 100;
as a new type TYPE TAB:array [Smax] of typedef int TAB [Smax];
integer TAB A; 7
VAR A : TAB
DEFINITIONS
In static arrays, a distinction is often made between the maximum size (or
declared size) and the real size (or used size) of the arrays.
maximum (declared) size real (used) size
Definition It represents the total capacity of the It represents the number of elements
array, meaning, the maximum number actually used in the array at a given
of elements that the array can store. time.
Declaration It is determined at the time of It is determined during execution
and declaration and remains fixed (usually by a reading) and may vary
modification throughout the life of the array. depending on the applicative logic.
Remark The size should not be too large to It must be less than or equal to the
avoid wasting memory. maximum size of the table.
8
DEFINITIONS
Access to an element of the array is done by specifying the name of the array
followed by the value of the index in square brackets for each dimension:
identifier [index1] [[index2]…. [index3]]
with indexd: a constant, a variable or an integer expression whose value
must be between 0 and (Smaxd – 1).
EXAMPLE 1 (Vector):
Nbr: array [9] of integer
The third element is
9
in position 2.
DEFINITIONS
EXAMPLE 1 (Vector):
A COEF array containing the coefficients of 7 courses
6 4 5 3 2 2 1
COEF: array [7] of integer 0 1 2 3 4 5 6
The following actions can be written
ACOEF[3] ; B COEF[k] ; CCOEF [ (test+k) MOD i ]
COEF[6] E ; COEF[ m ] F ; COEF[a*res DIV 2]G
It is noted that an element of the array is considered as a variable and that
the value of the index can be a constant, a variable or an expression whose
10
value must be between 0 and 6 (Smax-1).
USUAL VECTOR OPERATIONS
The usual operations on vectors (or one-dimensional arrays) include :
1. Vector Initialization
Empty initialization: create a vector without initial values.
Initialization with given values, for example, values read from the keyboard
(reading elements of a vector).
Initialization with a default value (zeros or others).
11
USUAL VECTOR OPERATIONS
Note 1 (Initialization): In C language, static arrays can be initialized
when they are declared. The initialization can be done by specifying the
values between the brackets { } when declaring. If values are not specified, the
array items are initialized with default values (0 for numeric types).
Declaration Array Image
int T1[3] = {8, 1, 12}; 8 1 12
int T2[8] = {1, 5, 1} 1 5 1 0 0 0 0 0
int T3[] = {10, 5, 8, -1}; 10 5 8 -1 12
USUAL VECTOR OPERATIONS
Note 1 (Initialization):
It is always possible to initialize an array using a loop in the body of the main
program or module.
For example, the array T can be initialized in different ways:
Initialization Langage Algorithmique (LA) Langage C (LC)
T : array [20] of integer int T [20];
with a single for i0 to 19 do T[i]c; for (i = 0 ; i<20 ; i++) T[i]=c;
constant (c)
with different for i0 to 19 do T[i] i; for (i = 0 ; i<20 ; i++) T[i]=i;
constants
with reading values for i0 to 19 do scan(T[i]); for (i = 0 ; i<20 ; i++) 13
scanf("%d", &T[i]);
USUAL VECTOR OPERATIONS
The usual operations on vectors (or one-dimensional arrays) include :
1. Vector Initialization
Empty initialization: create a vector without initial values.
Initialization with given values, for example, values read from the keyboard
(reading elements of a vector).
Initialization with a default value (zeros or others).
2. Browse
Browse the vector to display, modify or perform calculations on elements.
Copy one vector to another. 14
USUAL VECTOR OPERATIONS
Note 2 (Assigning one array to another)
The declaration of an array reserves space in memory for the elements of the
array and provides the address of the first element of the array in the name of
the array (without brackets).
Example:
tab: array[10] of integer
15
USUAL VECTOR OPERATIONS
Note 2 (Assigning one array to another)
The name of the array actually matches the address of the first item in the
array. This implies in particular that no global operations are allowed on a
array. In particular, an array cannot appear to the left of an
assignment operator.
For example, “T1
T2;” cannot be written. The assignment must be made
for each of the elements of the table using a loop:
Algorithmic Language (AL) C Language (CL)
Copy one array to Const N = 50 Const int N = 50;
another T1, T2 : array [N] of integer int T1 [N], T2[N]; 16
for i0 to N-1 do T1[i]T2[i]; for (i = 0 ; i<N ; i++) T1[i]=T2[i];
USUAL VECTOR OPERATIONS
The usual operations on vectors (or one-dimensional arrays) include :
3. Research
Find an element in the vector (exact value or specific criterion (minimum,
maximum, …..).
Find the number of occurrences of an element in the vector.
4. Sorting
Sort the vector in ascending or descending order, with algorithms such as
sorting by insertion, by selection, by bubbles, etc.
17
USUAL VECTOR OPERATIONS
The usual operations on vectors (or one-dimensional arrays) include :
5. Insert (add) Elements
Add an element at the end (an operation often called "push back").
Insert an element at a given position, which may require an offset of the
following elements.
6. Remove (delete) Elements
Delete an item at a given position, shifting the remaining items.
Delete the last item (often called "pop back").
18
USUAL VECTOR OPERATIONS
The usual operations on vectors (or one-dimensional arrays) include :
7. Mathematical operations
Calculation of the sum, the product, or the average of the elements.
Normalization (e.g., dividing each item by the total sum).
Element-by-element operations, such as adding a constant to all elements.
8. concatenation
Combine two vectors to create a new one.
19
USUAL VECTOR OPERATIONS
The usual operations on vectors (or one-dimensional arrays) include :
9. Rotation and Offset
Shift items to the left or right.
Circular rotation (the last item returns to the beginning, or vice versa).
10. Filtering.
Create a sub-vector from a criterion (for example, keep even elements only).
11. ……. Etc
20
STRINGS
A string is a sequence (or suites) of characters, usually seen as a sentence or
words.
It is written in quotation marks (double quote), e.g.: "HELLO", "Give the value
of X".
It is considered a structured type (an array of characters): a one-dimensional
array (vector) of which each element contains a single character.
Access to an element (character) is identical to that of vectors.
A string variable can be declared in two different ways: a character vector or
an abstract type called String. 21
STRINGS
Character vector String
Declaration ch: array [100] of caracter ch: string [100]
Reading Do scan(ch);
print("Give n between 1 et 100"); /*the real length "n" is
scan(n); calculated because the string
while (n<0) or (n>100); ends with a special null
For i0 to n-1 do character '\0' (pronounced
Begin "backslash zero" or "null
print("Give a ieme charater"); terminator") that indicates
scan (ch[i]); the end of the string.
EndFor; n 0
While (ch[n] != '\0‘) Do 22
n++
*/
STRINGS
Character vector String
Declaration ch: array [100] of char ch: string [100]
Writing For i0 to n-1 do print (ch[i]);
print (ch)
Example1 //Reading //Reading
"Hello" n5; ch[0] = 'H'; ch[1] = 'e'; ch[2] = ch "Hello »
'l'; ch[3] = 'l'; ch[4] = 'o';
H e l l o H e l l o \0
23
//printing //printing
Hello Hello
STRINGS
Assignments and comparisons are only done by for a single character.
Example
1. p,q: char ; /* p and q are characters */
2. chaine1: array [10] of char; chaine2: string
3. p ’A’ ; /* valid instruction */
4. chaine1 "Bonjour" ; /* INVALID instruction (A) */
5. chaine2 "Hello" ; /* valid instruction */
6. if (p = q) ; /* valid instruction */
7. if (chaine1 = chaine2) /* INVALID instruction (B) */
To make the assignment (A) and the comparison (B), it would
therefore be necessary to proceed character by character.
24
STRINGS
In C language, a string is a vector of characters that can be declared in
different ways: char ch[Smax], char ch [] or char * .
There is no abstract type of string, but there is a library <string.h> that
contains several modules for manipulating strings.
In this course (or even the PWs of this semester), we will use only the
declaration char ch[Smax] (where Smax is a constant), and we will return to
the other notions (dynamic declaration or declaration as much as pointer and
the modules of the <string.h> library) in semester 2.
25
STRINGS
The scanf and printf formatted input-output functions can read and write
strings with the format %s.
The scanf function reads on the standard input a sequence of characters up to
(and this is its main disadvantage) the encounter of a space spacing character,
tab or line break, arranges it at the indicated address and completes it with
a\0 symbol.
For example:
26
STRINGS
The scanf and printf formatted input-output functions can read and write
strings with the format %s.
The scanf function reads on the standard input a sequence of characters up to
(and this is its main disadvantage) the encounter of a space spacing character,
tab or line break, arranges it at the indicated address and completes it with
a\0 symbol.
For example:
27
STRINGS
The spacing character between Bonne and journée ends the reading.
However, it is common to have to read a line, that is to say a string of
characters containing several words spaced by spaces or tabs and ending with
a line break character\n.
To read a full line, you can use the fgets function, the prototype of which is as
follows:
char *fgets (char *s, int size, FILE *stream ) ;
It is actually a function that can be read from files but can be used to read
from the standard input stream (stdin). This function reads at most size-1
from the stream (which we can replace with stdin) and stores them in the
character string s . Playback stops after EoF or a line break. A null 28
character\0 is added at the end of the string.
STRINGS
char *fgets (char *s, int size, FILE *stream ) ;
It is actually a function that can be read from files but can be used to read
from the standard input stream (stdin). This function reads at most size-1
from the stream (which we can replace with stdin) and stores them in the
character string s . Playback stops after EoF or a line break. A null
character\0 is added at the end of the string.
For example:
29
MATRIXES
Matrixes seen in mathematics frequently appear in
algorithms and programming, because they constitute a
very natural format for storing data (images, screens,
animations, databases, game boards,etc.).
In a mathematical context, a matrix is an array with n
rows and m columns (n, m ∈ N) that contains numbers
(integers, real, complex, ...).
In an algorithmic context, a matrix is a two-dimensional
array that contains elements of simple (real, integer,
character, Boolean) or structured (array, string, record,
set) type. 30
MATRIXES
A matrix is declared as follows
Identifier: array [SmaxLig][SmaxCol] of type;
Where,
Identifier: Represents the name of the matrix.
SmaxLig: is the maximum number of rows.
SmaxCol : is the maximum number of columns.
Type: is the type of single or compound elements.
To access the elements of a matrix, we use the operator [ ] by specifying a
position by dimension: we first specify the row number, and then the column
number: 31
MATRIXES
Several operations can be performed on the matrices:
Consulting Operations Modification operations
• Displaying a matrix • Reading (entering or filling in) a
• Calculation of the sum, the product, the matrix
maximum, the minimum, the transpose, the • Edit elements
inverse,... for the elements of the matrix • Items offset
• Check the properties of a matrix: diagonal,
symmetrical, magic, etc.
All these operations require the elements of the matrix to be traversed. There
are several types of paths: row by row, column by column, partial, a row
/column, the main diagonal/secondary diagonal, etc. 32
MATRIXES
Exercise 1: Let a matrix A of size n*m (n≤20, m≤30), write an algorithm that:
1. Reads (fills in) the values of matrix A with two different methods (by row
and by column).
2. Displays the maximum as well as the average of all elements of A.
3. Constructs matrix B which represents the transpose of matrix A.
4. Displays the sum of each column of B.
5. Displays matrix A row by row, and matrix B column by column.
33
MATRIXES
Exercise 1 Solution:
Algorithm Operations_Matrice1;
Var
A : array of [20] [30] of integer; B: array of [30] [20] of integer;
i, j, n, m, S, Max : integer; Moy : real;
// 1. Read Matrix A
Do Do
print("give n between 1 et 20 "); print("give m between 1 et 30 ");
scan(n); scan(n);
while (n<1) or (n>20); while (n<1) or (n>30);
34
MATRIXES
Exercise 1 Solution:
// 1. Read Matrix A
//reading by row //reading by column
For i 0 to n-1 do For i 0 to m-1 do
For j1 to m-1 de For j1 to n-1 de
Begin Begin
print(“give an element“); print(“give an element“);
scan(A[i][j]); scan(A[j][i]);
EndFor; EndFor;
35
MATRIXES
Exercise 1 Solution:
// 2. Display the maximum as well as the average of all the elements of A
S0; MaxA[0][0];
For i 0 to n-1 do
For j0 to m-1 de
Begin
SS+ A[i] [j];
if(A[i] [j]> Max) then Max A[i] [j];
EndFor
MoyS/(n*m);
36
Print(“Moy=“, Moy, “ Max=“, Max);
MATRIXES
Exercise 1 Solution:
// 3. Construct matrix B which represents the transpose of matrix A.
For i 0 to n-1 do
For j0 to m-1 de
B[j][i]A[i] [j];
// 4. Display the sum of each column of B.
For i 0 to m-1 do
Begin
S0;
For j0 to n-1 de
SS+ B[j] [i];
37
Print("la somme des éléments de la colonne", i, " de la matrice B est :", S);
EndFor
MATRIXES
Exercise 1 Solution:
// 5. Display matrix A row by row, and matrix B column by column.
//Display by row //Display by column
For i 0 to n-1 do For i 0 to m-1 do
For j1 to m-1 de For j1 to n-1 de
print(“A[“, i, “] [“, j, “]=“, A[i][j]); print(“B[“, i, “] [“, j, “]=“, B[i][j]);
38
COURSE SOURCES
B. CHERGOU (2014), N. MEDJAOUI (2018) & N. BERREHOUMA, Cours d’algorithmique/pascal, 1st-
year CPI, Higher National School of Computer Science (ESI) Oued Smar, Algiers.
M. ZAIR (2022), Algorithmique 1, 1st-year License Common Core MI (Mathematics and Computer
Science), Faculty of Sciences, Saad Dahlab University, Blida.
O. Hadj Yahia (2022), Bureautique, algorithmique et langage de programmation, 1st-year License
Common Core SM, Faculty of Sciences, Saad Dahlab University, Blida.
M. Le Gonidec, INTRODUCTION A LA PROGRAMMATION– PRATIQUE DU LANGAGE C
–University of SUD, Disponible: [Link]
programmation-pratique-du-langage-c-et-c
39