Array Basic Program in C++


An Array refers to a collection of elements of similar data-types. This is particularly useful when the number of variables needed is in a big number. If we were to create variable names for every different variable then very soon we would run out of logical names to represent them. But Arrays make our work easier in this case. 

Arrays have the property that they carry the same name for a group of different distinct variables but all the variables have a different index to them. This index distinguishes each variable from any other variable. Also, the variables make the referencing of these elements very easy. 

When used in loops, these Arrays can prove to be a huge time saver. The loop variable can be used to index the Array inside the loop to give powerful control over the operations that have to be performed on the whole array.


Array elements are stored in consecutive memory locations according to the size of the datatype involved. If the datatype is of 2 Byte each, then every 2 Bytes from the starting memory location we shall find a new element of the Array in sequential order. A main benefit of this model is that if we know the memory location of the base element or first element then we can easily multiply by the fixed number of Bytes to obtain the location of a required element on a required index.

#include <iostream.h>
#include <conio.h>
int main()
{
      clrscr();
     
      int *p, i;
     
      p = new int [10]; // allocate 10 integer array
     
      for(i=0; i<10; i++ )
     
      p[i] = i;
     
      for(i=0; i<10; i++)
     
      cout << p[i] << " ";
     
      delete [] p; // release the array
     
      getch();
     
      return 0;
}

No comments:

Post a Comment

Custom Search