Chapter 05
Chapter 05
2.4. Initialization
In C, you can specify initial values for all array elements using curly braces { and } during array declaration.
Values are separated by commas ",", and these values must be of the same type.
Algorithms and data structures 1 Chapter 5: Arrays and Strings
Example
int tab[] = {15, 7, -2, 0, 9, 2, 0, -3};
index 0 1 2 3 4 5 6 7
value 15 7 2- 0 9 2 0 3-
Note: You can specify the number of elements between the two square brackets "[ ]", or leave them empty
for automatic calculation.
2.5. Usage
An array cannot be treated as a single block like array * 10; each element must be treated separately. To
access a single element of the array, we use the array name with an index inside square brackets [ and ], and
the expression inside the brackets evaluates to an integer value. To access the first element of array 'tab', we
use tab[0]. To access the fourth element, we use tab[3].
tab[5-3]tab[tab[3]+1] tab[2]tab[0+1] tab[2]7 مثال
le tableau devient
Indice 0 1 2 3 4 5 6 7
valeur 15 7 7 0 9 2 0 -3
Note: Accessing an element that doesn't exist (if the index is greater than or equal to the array size or
negative) will cause the program to terminate.
2.6. Reading an Array
To fill an array of N numbers, we use "read" N times like:
Algorithm C
Read (tab[0]) scanf("%d", &tab[0]);
read (tab[1]) scanf("%d", &tab[1]);
… …
read (tab[N-1]) scanf("%d", &tab[N-1]);
However, we notice that the read instruction is repeated N times, iterating from 0 to N-1. Therefore, the
"for" loop can be used, with the counter playing the role of the index.
Algorithm C
for i0 to N-1 do for(i = 0; i < N; i++){
write("nb", i, "") printf("nb %d ", i);
// Just to clarify // Just to clarify
read(tab[i]) scanf("%d", &tab[i]);
end for }
The "read" instruction is to fill the table, and the "write" instruction is to show the user what is required.
2.7. Displaying an Array
Like reading, "write" repeats.
Algorithm C
for i0 to N-1 do for(i = 0; i < N; i++){
write(tab[i]) printf("%d\t", tab[i]);
end for }
2.8. Observations
- To visit all elements of an array, we generally use the "for" loop.
- The array size must be specified during programming (declaration), but we can give the user the
impression that the array size can be changed by declaring a large array and using only part of it. We
ask the user for the desired size, it must not exceed the actual array size.
2.9. Example
Write a program that receives the averages of N students, where N is determined by the user, then calculates
the number of students who failed the subject (average less than 10).
Algorithms and data structures 1 Chapter 5: Arrays and Strings
Algorithm C
Algorithm nb_adjourned #include<stdio.h>
Const MAX=200 #define MAX 200
var avg[MAX] :array of real int main(){
i, aj, N : integer float note[MAX] ;
begin int i, N, aj=0; // aj is nb of adjourned
do // retrieve number of students
write ("enter number of students (<", do{
MAX, ")") printf("enter number of students
read (N) (<%d)",MAX) ;
while N>MAX scanf("%d",N) ;
for i0 to N-1 do }while (N>MAX) ;
write ("mark ", i, "") // Fill in the table
read (avg[i]) for(i = 0; i < N; i++){
end for printf("avg %d ", i);
aj 0 scanf("%d", ¬e[i]);
}
for i0 to N-1 do
if avg[i]<10 then // calculate number of adjournments
for(i = 0; i < N; i++)
ajaj+1 if(avg[i]<10) aj++ ;
end if // result display.
end for printf("the number of adjourned is %d",
write("the number of adjourned is ", aj) aj);
end }
3. Multi-Dimensional Arrays
3.1. Definition
A two-dimensional array (also called a matrix) is essentially a simple array (one-dimensional) whose
elements are themselves one-dimensional arrays. We see this in the illustration below,
0 1 2 3
The elements are accessible via two indices, the first specifying the row number and the second specifying
the element number in that row (column).
This mechanism can be generalized to create matrices with more than two dimensions. We can create an n-
dimensional array, and accessing its elements requires n indices. The arrangement of indices is crucial. The
element M[3][2] (36) is different from the element M[2][3] (28).
3.2. Representation
The matrix is represented in memory by a sequence of adjacent cells. A cell cannot be removed or added to
the matrix after its creation (static). The following figure represents a matrix with 3 rows and 5 columns of
real numbers.
Column Number
0 1 2 3 4
0 15 7 -3 0 9
Row Number
1 6 12 4 33 55
2 2 -8 17 25 -52
3 14 42 36 49 -12
3.3. Declaration
Algorithm C
matrixName[Rows][ Columns] : Array of elementType elementType matrixName [Rows][ Columns] ;
The term "Array of" is a reserved word in the algorithm, used to indicate that the variable is an array.
- `matrixName`: The identifier given to the matrix (variable name).
Algorithms and data structures 1 Chapter 5: Arrays and Strings
3.4. Initialization
In C, the initial values of all matrix elements can be specified by specifying the elements of each row
between `{` and `}`, along with the matrix declaration. The values are separated by commas `,`, and each
row is separated by a comma `,`. All values must be of the same type.
Example:
int mat[][] = {{15, 7, -3 ,0 ,9},{6, 12, 4,33,85},{2, -8, 17 ,28,-52},{14, 42, 36, 49, -12}};
column number
0 1 2 3 4
0 15 7 3- 0 9
Row Number
1 6 12 4 33 55
2 2 5- 17 25 52-
3 14 42 36 49 12-
Note: You can specify the number of rows and columns between the two brackets or leave them empty to be
calculated automatically.
3.5. Usage
To access a single element of the matrix, we use the matrix name with an index inside two brackets `[` and
`]` specifying the row number, and another index inside two brackets `[` and `]` specifying the column
number. To access the element in the first row and first column of matrix `mat`, we use `mat[0][0]`.
syntax mat[line][column]
example mat[1][3]mat[1][3]+2
the matrix becomes
Column number
0 1 2 3 4
0 15 7 3- 0 9
Row Number
1 6 12 4 35 55
2 2 5- 17 25 52-
3 14 42 36 49 12-
3.6. Reading a Matrix
To fill the matrix `M[Rows][Columns]`, we fill in `Rows` rows. Since each row is a one-dimensional array
with `Columns` elements.
Algorithm C
for j0 to C-1 do for (j=0 ;j<C ;j++)
read(M[0][j]) scanf("%d", &M[0][j]);
end for for (j=0 ;j<C ;j++)
for j0 to C-1 do scanf("%d", &M[1][j]);
read(M[1][j]) …
end for for (j=0 ;j<C ;j++)
… scanf("%d", &M[L-1][j]);
for j0 to C-1 do
read(M[L-1][j])
Algorithms and data structures 1 Chapter 5: Arrays and Strings
end for
However, we notice that the `for` loop is repeated `Rows` times. In other words, it iterates from 0 to `Rows -
1`. Therefore, the outer `for` loop can be used.
Algorithme C
for i0 to L -1 do for(i = 0; i < L; i++)
for j0 to C-1 do for(j = 0; j < C; j++){
read(M[i][j]) printf("M[%d, %d] ", i,j);
end for scanf("%d", &M[i][j]);
end for }
The `read` statement is used to fill the matrix, and the `write` statement is used to explain to the user what is
required. The `for(j ...)` loop contains two `printf` statements to explain and a `scanf` to enter values. The
`for(i ...)` loop contains only one `for(j ...)` loop statement.
Explanation of `write`: Let's assume `i = 3` and `j = 5`
write( "M[" i "," j "]"
screen M[ 3 , 5 ]
3.7. Displaying a Matrix
Similar to reading, the `write` statement is repeated.
Algorithm C
pour i0 à L-1 faire for(i = 0; i < L; i++){
pour j0 à C-1 faire for(j = 0; j < C; j++)
write(M[i][j]) printf("%d\t", M[i][j]);
finPour printf("\n") ;
finPour }
The `for(j ...)` loop contains the `printf` statement to print element `M[i][j]`. The `for(i ...)` loop contains two
`for(j ...)` loops for printing row `i`, and `printf("\n")` to move to the next line at the end of each row `i` of
the matrix.
Note: To visit all elements of the matrix, we use two `for` loops.
3.8. Example
Write a program that reads hourly temperatures for 30 days as a matrix (30 by 24), then displays them on the
screen. After that, display the highest temperature and when it was recorded.
Algorithm C
Algorithm temperatures #include<stdio.h>
Const Dy =30 Hr=24 #define Dy30 // nb lignes
var T[Dy][Hr] :array of real #define Hr 24 // nb colonnes
int main(){
maxT :real
float T[Dy][Hr] ,maxT; // max température
i, j,maxDy,maxHr :integer
int i, j, maxDy,maxHr;
begin
// Fill in temperatures
for i0 to Dy-1 do for(i = 0; i < Dy; i++)
for j0 to Hr-1 do for(j = 0; j < Hr; j++){
write ("T[", i+1, ",", j, "]") printf("T[%d, %d] ", i+1,j);
read (T[i][j]) scanf("%d", &T[i][j]);
end for }
end for // display all temperatures
for i0 to Dy-1 do for(i = 0; i < Dy; i++){
for j0 to Hr-1 do for(j = 0; j < Hr; j++)
write (M[i][j]) printf("%d\t", M[i][j]);
end for printf("\n") ;
end for }
maxTT[0][0] // search for maximum temperature
maxDy0 maxT=T[0][0];
maxDy =0 ;
maxHr0
maxHr=0 ;
for i0 to Dy-1 do for(i = 0; i < Dy; i++)
for j0 to Hr-1 do for(j = 0; j < Hr; j++)
if (T[i][j]>maxT) then if (T[i][j]>maxT){
Algorithms and data structures 1 Chapter 5: Arrays and Strings
maxTT[i][j] maxT=T[i][j];
maxDyi maxDy =i;
maxHr=j;
maxHrj
end if }
end for // display of results
end for printf("the maximum temperature is %d and
was recorded on %d at %d", maxT, maxDy
write("the maximum temperature is ",
+1, maxHr) ;
maxT," and was recorded on ", maxDy+1,
}
" at ", maxHr )
end
The program takes the temperature matrix `Temperatures` and outputs the highest temperature recorded
`maxTemp`, the day it was recorded `maxDay`, and the hour it was recorded `maxHour`. After filling the
matrix and displaying it, we assume that the highest temperature is in row 0 and hour 0. Then we go through
all elements of the matrix, and if we find a temperature higher than the one stored in `maxTemp`,
`maxTemp` changes, and so do `maxDay` and `maxHour`. In the end, we display the results on the screen,
incrementing `maxDay` by 1 since rows start from 0 and days start from 1.
4. Strings
4.1. Definition
A string is an ordered set of characters, zero or more. They are always enclosed in double quotation marks
`"` such as "computer", "Good luck\n", "1", "3.14". In C, character arrays are used to create strings. When
you read a string from the keyboard, each character is placed in a location, and when the characters are
finished, the character '\0' is added to the end of the text to indicate its end. The character '\0' is called "null,"
with a code of 0. There is a constant declared in the stdio.h library called NULL in uppercase.
#define NULL 0
Note: Since each character has a code, for example, the code of 'A' is 65, the code of 'a' is 97, similarly, the
character '\0' has a code which is 0. NULL? '\0' ? 0.
NULL ‘\0’ 0
4.2. Declaration
In algorithms, we use the string, while in C, we use a character array. Suppose we have the string `str`,
which can contain a maximum of 30 characters, including '\0'. It is declared as follows:
var str : string char str[30] ;
var str[30] :array of characters
4.3. Initialization
In the following example, we create a character array and initialize it with the word "Welcome."
char greeting[] = {'W', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
This statement creates an 8-character array (7 slots for the word "Welcome" and one slot containing the
character '\0'). However, there is a simpler and faster way to create and initialize a string:
char greeting[] = "Welcome";
This leads to the same result, which is creating an 8-character array, ending with the character '\0'.
0 1 2 3 4 5 6 7
greeting W e l c o m e \0
The size of the array can also be specified:
char greeting[00] = "Welcome";
0 1 2 3 4 5 6 7 5 … 28 29
greeting W e l c o m e \0 …
4.4. Assignment
Since strings are arrays, a string cannot be assigned to a variable directly after its declaration. The following
operation is incorrect:
Algorithms and data structures 1 Chapter 5: Arrays and Strings
char slt[00];
slt = "Welcome";// error : assignment to an array.
To assign a string to a variable or copy one variable to another, we use the `strcpy()` function.
strcpy(slt , "Welcome" );