Array Initialization
The automatic array cannot be initialized, unlike automatic
variables. However, external and static arrays can be initialized if it is
desired. The initial values must appear in the same order in which they will be
assigned to the individual array elements, enclosed in braces and separated by
commas.
The general format
of the array initialization is,
storage_class data_type
array_name [expression]=.
{ element_1, element_2...element_n };
Where the storage_class is used to declare the
scope of the arrays like static, automatic or external; data_type is the nature of data elements such as integer, floating,
or character etc.; the array_name is
used to declare the name of the array; and the elements are placed one after
other within the braces and finally ends with the semicolon.
For example,
int values [7] = { 10,11,12,13,14,15,16 };
float coordinate [5] = {
0,0.45,-0.50,-4.0,5.0 };
char sex [2] = {‘M’ , ’F’};
char name [5] = { ‘R’ , ’a’ , ’v’ ,
’I’ , ’c’ };
The result of each of the above array element are:
values [0] = 10
values [1] = 11
values [2] = 12
values [3] = 13
values [4] = 14
values [5] = 15
values [6] = 16
coordinate [0] = 0
coordinate [1] = 0.45
coordinate [2] = -0.50
coordinate [3] = -4.0
coordinate [4] = 5.0
sex [0] = ‘M’
sex [1] = ‘F’
name [0] = ‘R’
name [1] = ‘a’
name [2] = ‘v’
name [3] = ‘i’
name [4] = ‘c’
Note that in C++,
the first element is always placed in the 0th place; it means that
the array index starts from 0 to n-1, where
n is the maximum size of the array declared by the programmer.
Some unusual way of
initializing the array elements are discussed below. For example, if the array
element are not assigned explicitly, initial values will be automatically set
to zero. Considered the following array declaration,
int number [5] = {1,3,2];
For the above, the
elements will be assigned to the array in the following way:
number [0] = 1
number [1] = 2
number [2] = 3
number [3] = 0
number [4] = 0
No comments:
Post a Comment