blog

Home / DeveloperSection / Blogs / Concept of Array

Concept of Array

Anonymous User4775 31-Aug-2010
An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. For example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type (eg. int) with a unique identifier.An array is an ordered sequence of scalar data. All the elements of an array have the same type and type parameters.
Like other variables an array must be declared before it is used. For example, if we want to store 10 elements of integer type then we will declare it like
int i[10];
Once the array is declared we can store elements in the array. There are
two ways to initialize array:
i) Initialize during the declaration time: If we are initializing the array element during the declaration time then there is no need to specify the number of elements in the array, but if we want to then we can.
Eg.
int i[]={1,2,3,4,5,6,7,8,9,10};
Or
 Int i[10]={1,2,3,4,5,6,7,8,9,10};
Both of the above statements are correct.
ii) Initializing during runtime or one by one: We can store data in the array during runtime. During runtime we can take user input to initialize the array or through a loop.
Eg.
int i[10];
for( int k = 1; k <= 10; k++)
  i[k] = k*2;
Or
int i[10];
for(int k = 1; k <= 10; k++)
    cin>>i[k];
For retrieving the values of array we can use the index of array element.
Eg.
cout<<i[3];
Or for viewing the whole array we can use loop.
Eg.
for(int k = 1; k <= 10; k++)
cout<<i[k];
Two Dimensional Array
Two dimensional array can be referred as array of array. A two dimensional array can be imagined as a table, having rows and columns where every row is an array. To declare two dimensional array we have to provide both rows and columns.
Eg.
int i[2][3];
The above code will declare an array of 2X3, i.e. 2 rows and 3 columns. To access the array we will have to provide both row and column. For example, if we want to access or display 3rd element of 2nd row then we have to write
cout<<i[1][2];
Index number is always one less than the element as index number starts with ‘0’.
 

Updated 18-Sep-2014
I am a content writter !

Leave Comment

Comments

Liked By