# Lesson 9.2. Array initialization

## Syntax

In C, an array can be initialized in its entirety at the time of its declaration and only at the time of its declaration. The syntax consists in putting between two braces the values of the cells separated by commas:

int tab[5] = { 12, 25, 65, 11, 7};

This initialization creates an array with the following values:

$$tab = \begin{bmatrix} 12 \\ 25 \\ 65 \\ 11 \\ 7 \end{bmatrix}$$

If the number of values between the braces is less than the size of the table, only the first cells (concerned) will be initialized.

When initializing at the declaration, if the size of the table is not specified between the square brackets, the size of the table will automatically adapt. For example, the following line creates an array of 3 cells:

int tab[] = {1,2,3};

If you have to initialize an array outside its declaration, you have to

• either initialize it cell by cell ;
• or copy a memory block directly with the memcpy() function.

## Exercises

### Exercise 1

Write a program that creates declares and initializes an array with the first 5 odd numbers. The program then displays the contents of the array according to this example:

tab[0] = 1
tab[1] = 3
tab[2] = 5
tab[3] = 7
tab[4] = 9


### Exercise 2

Modify the code of the previous exercise so that the table now contains the 1000 first odd numbers :

tab[0] = 1
tab[1] = 3
tab[2] = 5
...
tab[997] = 1995
tab[998] = 1997
tab[999] = 1999


## Quiz

Which syntaxes can be used for initializing an array?

How to initialize an array outside its declaration?

Let's consider the following initialization. What is in tab[2]?

int tab[3] = { 10, 20 };

What is the size of this array?

char tab[] = { 10, 20, 30, 40 };