Till the array elements are not given
any specific values, they are supposed to contain garbage value. The values can
be assigned to elements at the time of array declaration, which is called array
initialization. The syntax is
Storage_class data_type array_name[expression]={vaue1, value2, …value
n};
Where, value1 is value of first
element, value2 is that of second and so on.
The array initialization is done as given below:
int a[5]= {1,2,3,5,8};
int b[]= {2,5,7};
int c[10]={45,89,54,8,9};
In first example, a is
integer type array which has 5 elements. Their values are assigned as 1, 2, 3,
5, 8 (i.e. a[0]=1, a[1]=2,a[2]=3,a[3]=5 and a[4])=8. The array elements are
stored sequentially in separate locations.
In second example, size
of array is not given, it automatically its size as 3 as 3 values are assigned
at the time of initialization. Thus, writing int b[]= {2,5,7}; and int b[3]= {2,5,7}; is same.
In third example, the
size of array c has been set 10 but only 5 elements are assigned at the time of
initialization. In this situation, all individual elements that are not
assigned explicit initial values will automatically be set to zero. Thus, the
value of c[5]=0, c[6]=0 …… c[9]=0.
Comments
Post a Comment