Google+

Wednesday, 3 December 2014

Algorithm: Array : Post 6

Array :

           An array is a data structure (linear data structure) which can store a fixed number of elements of the same data type.
An array is used to store a collection of data, but in a simpler way we can think of it as a collection of variables of the same type.




Let us consider an array as a shelf with partition, Each partition is numbered and can store only a single book, (only books can be stored in shelf).

Similarly an array of integer can store a single integer in one block, and the total array is collection of such blocks.




eg. Say we have to store ten numbers, 1, 5, 6, 3, 0, 66, 20, 18, 30, 35.

one way is


As you can see it is a long process and its maintenance is cumbersome.


So another and method can be storing all the elements in a array.

Both of these will give the same result


So obviously the array is a better option to store value.
and if you see closely, both of the program are taking same storage size that is 40 bytes, 
4 (int) x 10 (number of variables) ,
But in first there are 10 different references but in second on only one reference is enough. 


Creating an array:

                 In java:  <type> <array name>[] = new <type>[<size>];
                                 eg-  int array[]=new int[10];
                 In C    :   <type> <array name>[<size>]; 
                                 eg- int array[10];

Initialization:


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

or 

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

or

initializing each element individually 
array[0]=1; array[1]=2; array[2]=3; array[3]=4; array[4]=5;


similarly we can use or utilize the array.
Important point to remember about array is that it can be accessed randomly using the number of the array position.
eg: to get 5th element just write array[5]; 


Array can be multidimensional too,
eg: 2d, 3d etc.

2d array is like matrix,
a array of 2 row and 3 column will be like

to create a 2d array,   int array[2][3];
now lets fill the array, 
               array[0][0]=0;
               array[0][1]=1;
               array[0][2]=2;
               array[1][0]=3;
               array[1][1]=4;
               array[1][2]=5;
So now the array will be like 

Like wise we can have 3d and 4d and so on


Next post will be about Stack;

No comments:

Post a Comment