Initialization of Array

Initialization of Array

Published by: Nuru

Published date: 21 Jun 2021

Initialization of Array Photo

Initialization of Array

Initialization of Array is defined as assigning the specific values to the individual array elements at the time of array declaration. Since an array has multiple elements of the same data type, the braces we use are to denote the entire array. And, there is the use of commas to separate the individual values assigned to the individual elements in the array.

An array will not be initialized until it is declared. Therefore, its contents are undetermined unless we store some of the values in it. The array elements contain the garbage values in an uninitialized array. That means there is the only declaration.

One-Dimensional Array Initialization

Syntax:

storage_class data_type array_name [size] = [value 1, value 2, ….., value N];
Here in the syntax above, value 1 is the first element, value 2 is the second element, and so on.

For example:
int a[6] = [21, 13, 54, 5, 101, 77 ];

In the 'For Example' above, a is an integer type array having 5 elements.
Their values are initialized a[0] = 21, a [1] = 13, a [2] = 54, a[3] = 5 , a[4] = 101 and a[5] =77. There is toring of these sequentially in separate memory locations.

For Instance,

int marks [5];
This is the array of 5 integers. We can initialize the elements in an array in two ways. The first one is, there is a listing of the value of each element within two curly brackets { } and a comma (, ) to separate one value from the other.

marks [5] = { 45, 3, 65, 88, 60 };
or
marks [ ] = { 45, 3, 65, 88, 60};

Now, the second one is, each element can be initialized one at a time. Then it will look like:
marks [0] = 45  marks [1] = 3  marks [2] = 65  marks [3] = 88  marks [4] = 60;

We can also show these in the memory cells. Marking of these in the memory cells will look like below:

Initialization of Array

Multidimensional Array

In the initialization of a multidimensional array, we can take the example of a two-dimensional array.

We can initialize two-dimensional arrays by separating each element by commas and each row by { }. Let us take a two-dimensional array initialization.

For example:

int a [4] [2] = { { 12, 56}, {13, 33}, {14, 80}, {15, 78} };
We can also write it as:
int a [4] [2] = { 12, 56, 13, 33, 14, 80, 15, 78 };

We should remember that, while initializing a 2-Dimensional array, it is necessary to mention the second dimension, whereas the first one is optional.

Thus the declaration will be,

int a[2] [3] = {12, 34, 23, 15, 32, 54};
int a [ ] [3] = {12, 34, 23,15, 32, 54};

The declarations like below does not work.

int a [2] [ ] = {12, 34, 23, 15, 32, 54};
int a [ ] [ ] = {12, 34, 23, 15, 32, 54};