An array is a sequential sequence of cells, all of the same type. An array can have one or more dimensions. Here is an example of a declaration of an 5 cells integer array:
int tab[5];
An array can only contain cells of the same type. If you need to create an array that contains cells of different types (e.g. integers and floats), you have to create two arrays or use structures that we will see later in this course.
The syntax for the declaration of an array is illustrated below:
This statement creates a table that can be represented as rows or columns:
$$ tab = \begin{bmatrix} a_0 && a_1 && a_2 && a_3 && a_4 \end{bmatrix} $$
$$ tab = \begin{bmatrix} a_0 \\ a_1 \\ a_2 \\ a_3 \\ a_4 \end{bmatrix} $$
The numbering of the cells starts at zero. A table of n cells is numbered from 0 to n-1.
An element of the array can be accessed in read or write mode by using the name of the array followed by the indices between square brackets. For example:
// Declares an array of 5 integers
int tab[5];
// Assign 2 in the first cell
tab[0] = 2;
// Assign 12 to the last cell
tab[4] = 12;
// Check if there is 12 in the last cell
if (tab[4] == 12) printf ("OK\n");
Note: it is not possible to perform assignment or comparison operations on a table as a whole.
if (tab1==tab2)
does not compare arraystab1=tab2
does not copy tab2
in tab1
To compare two arrays or copy one array into another, you must do it cell by cell.
Write a program that creates an array of 10 cells and displays its contents (without initializing it). The display must be done with a loop according to the following example:
tab[0] = -309253648 tab[1] = 32550 tab[2] = 0 tab[3] = 0 tab[4] = 4195664 tab[5] = 0 tab[6] = 4195328 tab[7] = 0 tab[8] = 609240816 tab[9] = 32765
Using the code from exercise 1, write a loop that initializes
the first cell of the array with -1
, the second with -2
and so on:
tab[0] = -1 tab[1] = -2 tab[2] = -3 tab[3] = -4 tab[4] = -5 tab[5] = -6 tab[6] = -7 tab[7] = -8 tab[8] = -9 tab[9] = -10