Monday 1 October 2018

Input and output of two-dimensional array in C++

Two-dimensional array


A two-dimensional array is an array having a pair of square brackets(or having two dimensions). It is an example of multidimensional array. It has a double size specification. A two-dimensional array is used for the implementation of a matrix. When a two-dimensional array is implemented as a matrix, the first dimension represents the number of rows and the second dimension represents the number of columns. E.g. a[2][2], a[3][2], a[4][4].

An array a[2][2] will have four elements which are a[0][0]a[0][1]a[1][0]a[1][1].



Write a program in C++ to input the values of a two-dimensional array and display it.


In this program, we declare an array. Then we input the number of rows and number of columns the user wants in that array. Then we use a nested for loop for the input of array. The outer for loop will be executed for the number of rows. The inner nested for loop will be executed for the number of columns. We input the values of all the elements of the array from the user and display it using another nested for loop.


Program


#include<iostream.h>
#include<conio.h>
void main()
{
int a[20][20],m,n,i,j;
clrscr();
cout<<"Input of two dimensional array"<<endl<<endl;
cout<<"Enter the number of rows=";
cin>>m;
cout<<"Enter the number of columns=";
cin>>n;
if(m>20||n>20)
      {
cout<<endl<<"Invalid input";
goto x;
}
cout<<endl;
for(i=0;i<m;i++)
          {
for(j=0;j<n;j++)
{
cout<<"Enter the element in a["<<i<<j<<"]= ";
cin>>a[i][j];
}
          }
cout<<endl<<"Output of two dimensional array"<<endl<<endl;
for(i=0;i<m;i++)
          {
for(j=0;j<n;j++)
{
cout<<a[i][j]<<"\t";
}
          cout<<endl;
          }
x:getch();
}


Output


Program to input the values of a two-dimensional array.
INPUT AND OUTPUT OF TWO-DIMENSIONAL ARRAY













Explanation



In the above, we have entered an array with two rows and two columns(i.e. m=2 and n=2). The nested for loop of the input of array is executed as follows:

i(<m)           j(<n)                 a[i][j]      
0                  0                      a[0][0]=6
                    1                      a[0][1]=9
1                  0                      a[1][0]=8
                    1                      a[1][1]=3.


In this way, we input the values for a two-dimensional array. A similar nested loop is executed for the display of two-dimensional array and we obtain our output on the screen.





No comments:

Post a Comment