You are on page 1of 2

Array Basics

Here I am going to describe a very basic concept of programming, Array. A general definition of an array is a collection of similar data objects which are stored in consecutive memory location under a same variable identifier. But to understand this in a better way you must understand how variables are stored in memory. int x =10; //declaration and definition The above statement allocates a block of memory of size 2 (size of int) and name it x and also store a value 2 inside that address. Think it like a house built in a size of 200 sq yards with a nameplate outside as xyz villa and the person living inside is Mr. abc

Now lets say int egarray[5] = {6,3,5,8,9}; //declaration and defination So it will allocate 5 consecutive int and name it as exarray and store respective values in it. Here 5 is the size of array. Now the total memory allocated is 10 (5 * 2).

Now check out the values written in []. These are known as index, which refer to the elements in the egarray. Indexing in array is 0 based that means the very first element in the array is actually the 0th element and can be addressed as egarray[0] which here is equals to 6 and similarly egarray[1] = 3 egarray[2] = 5 egarray[3] = 8 egarray[4] = 9 So the elements in an array can be accessed as arrayname[index] where index is 0 to size-1 Lets see an example # include <iostream.h> #define SIZE = 3 void main (void) { int number[SIZE]; //line 1 //line 2 //line 3 //line 4 //line 5 //line 6

int i; for(i = 0; i <= SIZE-1; i++) { cout << Enter Element = ; cin >> number[i]; } for(i = SIZE-1; i >= 0; i--) cout << number[i]; }

//line 7 //line 8 //line 9 //line 10 //line 11 //line 12 //line 13 //line 14 //line 15 Program to enter elements in array and print it in reverse order

Note: There can be better way to reverse elements in array. This is just an example to show the usage of array. Here is the explanation for the above program: Line 2: Defined a variable named SIZE. Line 6 7: Declared an array number of type int and size SIZE. This means number can contain no. of elements equal to SIZE. Line 8 12: For loop will run from 0 to 2 and user will enter values in number[0], number[1], number[2] Line 13 14: For loop will run from 2 to 0 and display the values in number in reverse order i.e. number[2], number[1], number[0]

You might also like