Friday, 2 September 2016

Initialization of Array

                              INITIALIZATION OF ARRAY 

The array initialization can be done as under:

int a[5]={1,2,3,4,5};

Here 5 elements are stored in an array 'a'. List of elements initialized is shown within the braces.The elements are stored sequentially in separate locations.Then the question arises how to call individually to each element from this bunch of integer elements.

Reading of element begins from '0'.By indicating the position of elements, one can retrieve element of an array.Array elements are called with array names.

a[0] refers to 1st element i.e 1.
a[1] refers to 2nd element i.e 2.
a[2] refers to 3rd element i.e 3.
a[3] refers to 4th element i.e 4.
a[4] refers to 5th element i.e 5.

EXAMPLE:

To store more than one value the programming languages have an built data structure called an array .

  1.  int num[5] ;
          In the above declaration.an integer array of five elements is declared .Memories for five                       integers,i.e. successive 10 bytes ,are reserved for the num array.To initialize the num array                   following syntax can be used.



      2. int num[5] = {1,2,4,2,5};

          In the above statement ,all elements are initialized .It is also possible to initialize individual                 element by specifying the subscript number in the square bracket following the array name.
          Array elements are accessed as follows:

              num[0]=1;
              num[1]=2;
              num[2]=4;
              num[3]=2;
              num[4]=5;

The initialization can be done at the compile time or dynamic at the run time .The above is an example of compile time initialization./

In the above array, the element num[0]  i.e 1 is the lowest bound and num[4] i.e 5 is the last element .In c and c++ ,there is no  bound checking .Hence the programmer has to check it while accessing or storing elements.Once   the array is declared , its lowest bound cannot be changed but the upper bound can be expanded.The array name itself is a constant pointe,and therefore we cannot modify it. Storing elements in contigious memory locations can expand the upper bound.  


The array name itself is a pointer .The array num  is pointer to the first element i.e  num cotains address of memory locations where element 1 is stored .The address stored in the array name is called the base address .



To access individual elements,the following syntax is used:

num[0] refers to the 1

num[1] refers to the 2


num[2] refers to the 4


num[3] refers to the 2


num[4] refers to the 5


Thus, an array is a colection of elements of the same data type ,stored in unique and successive memory location.



No comments:

Post a Comment