How to define size of Array at run-time of the program?

Array size defined at Run time:

  Code

{

    int a[180][180], i, j, m, n; //180 is the max number of rows and columns that can be used for array
    

    cout<<"\nEnter the size of the Array(rows, column):\n";

    cin>>m>>n;

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

    //For entering elements of the Array

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

 } 


The general misconception about 2D-Arrays is that their size can't be defined at run time, but it is possible by this method. The reason is, in this program we make an array with maximum number of rows and columns possible and while run-time of the program we just use the number of rows and columns which are required by us. This code is useful when we don't know the size of array required by the user.

No comments:

Post a Comment