Initializing – When we declaring an array, the elements of the array has values according to the class of the array i.e. 0 value for static and extern and garbage value for auto and register.
Example:
int S[10]; //An Array S of 10 elements with initial value as Garbage value
In C it is also possible to initialize the elements of the array at the same place where they are declared i.e. in the beginning itself.
Initializing a One Dimensional
One dimensional array can be declared and initialized at the same place as
Example:
int S[10] = {50, 20, 70, 15, 75, 65, 67, 9, 55, 90};
In this case,
S[0] = 50, S[1] = 20,..., S[9] = 90
Note: In one Dimensional Array when we declare and initialize an Array at the same place, then to specify subscript value is optional.
Free E-books
So,
int S[] = {50, 20, 70, 15, 75, 65, 67, 9, 55, 90};
Example: float rate [] = {55.5, 75.6, 90.8, 20,0};
Example: char name[] = {‘H’, ‘T’, ‘T’, ‘E’, ‘N’};
Example: int i [10]= {10,20,30,40,50};
It will take first five elements as it is and next five as the garbage values.
Example: int i [5] = {5, 10, 15, 20, 25, 30, 35, 40};
Compiler will flag an error message as number of elements are more in the list than the declared size.
Free Hand-Written Notes
Initializing Two-Dimensional
- It can be treated as an array of one dimensional arrays.
- As one dimensional array, two dimensional array can also be declared and initialized at the same place.
- They can be initialized as
int a [4][5] = {
{0,1,2,3,4}, --Row 1
{5,6,7,8,9}, --Row 2
{10,11,12,13,14}, --Row 3
{15,16,17,18,19}, --Row 4
};
col1 col2 col3 col4 col5
- Where a is the name of the 2 dim. array of int type
- 4 is the first subscript i.e. number of rows
- 5 is the second subscript i.e. number of coloumns
The same array can be initialized as given below:
int a[4][5] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
In this case first five elements are assigned to first row, next five the second row, next five to third row and last five to the fourth row.
The problem in this version of initialization is that it is not as appropriate and understandable as the first one. So the first version is much better than this version.
Initializing a Three Dimensional
Three Dimensional Array can be looked like an array of two dimensional arrays and can be declared as well as initialized at the same place as givenbelow:
int m [2][3][2] ={
{
{0,1},
{2,3},
{4,5},
},
{
{6,7},
{8,9},
{10,11}
}
};
- Where m is the name of the array of int type
- 2 is the first subscript
- 3 is the second subscript
- 2 is the third subscript
The same can also be initialized as below:
int m [2][3][2] = {0,1,2,3,4,5,6,7,8,9,10,11};
Note: In two dimensional Array if we want to declare and initialize the array at the same place, first subscript is optional to specify, whereas second subscript is must.
e.g. a[][5] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};