Sunday, September 25, 2011

How Arrays Work? (Explanation with Animation)

Array  is a datatype available in the C language (and other languages also) to store similar type of data elements in contiguous memory locations. The word 'contiguous' is of precise importance here, as it brings the biggest advantage of arrays into picture - 'Faster access to data elements'  

Arrays in C store  datatypes work under a single variable with an index, also known as a subscript. An array is simply a list of variables of the same type.  As such, arrays often help a programmer organize collections of data efficiently and intuitively.
Its the most common data-structure used to store data. Arrays are basically easy to use and traverse. Arrays are popular due to many of its advantages (mentioned below) over other available  data structures in C  Language. Indexing is 0-based and the elements can be accessed in a constant time by using the index of the particular element a as the subscript.

Advantages of using arrays:

    * Easier to use and access
    * Faster access to the elements

Disadvantages of using arrays:

    * Fixed size - the size of the array is static (Can be made dymanic)
    * Complex position-based insertion - if you want to insert an element at a position already covered by some other element then you have to shift right by one position all the elements to the right of that position. This will vacate the position for you to insert the new element at the desired position. The more elements you have to the right of the desired position, the more expensive the process will be.


Example :

int a[5] = {1,2,3,4,5};
a[0] is nothing but value at the first position in the array , which is "1".
also if int i =0, then a[i] = a[0] = 1
Another important aspect is , a[i] is same as i[a].

char name[] = {'h' , 'e' , 'l' , 'l' , 'o' , '\0'}; here a null value '\0' is needed to mark the endof the array as its size is not specified. It can also be declared as char name[] = "hello";

So an array of char is nothing but a string/word and an array of strings is nothing but a sentence.
char string[] = "Who am I ?";

Animations on how arrays work with different functions like delete , insert , reverse etc.

Delete Function :


Insert Function :


Reverse Function :



----------------------------------------------------------------

No comments:

Post a Comment