Initialization of 2D-Arrays in C++

Pre-initialization method

Long Method

In this method we initialize the values of each element in the array separately.

Eg: int a[2][2];
   
      a[0][0]=4;
      a[0][1]=12;
      a[1][0]=8;
      a[1][1]=1;


Initializing at Declaration

In this method we enter the values of the elements of the array while declaring it.

Eg: int a[2][2]={4,12,8,1};


Disadvantages of these two methods is that the size and elements of the array is initialized before only.

General Method(Initializing at run time)

In this method we use a nested loop to enter the elements of the array at run time.

     Code

 {

    int a[row][column], i,  j; //row and column should be replaced with size of the array
     

    cout<<"\nEnter the elements of the Array:\n";

    //For entering elements of the Array

    for(i=0;i < row;i++)
     {
         for(j=0;j < column;j++)
         cin>>a[i][j];
     } 

 } 

No comments:

Post a Comment