2 D Array in C

What are 2 d array in C with Example?

  • The array is constructed from a number of rows and the number of columns is used to solve a real-time problem.
  • 2-D array in C is also known as a multi-dimensional array
  • They are used to store data that which requires two reference namely row number and column number
  • Hence, “matrix” is the best example of two-dimensional arrays
  • If a two-dimensional array i.e. matrix is to be declared of size 2 X 2 then the declaration statement will be: int a[3][3];
  • The representation of the 2-D array will be 2 X 2 i.e as shown below
a[0][0]a[0][1]a[0][2]
a[1][0]a[1][1]a[1][2]
a[2][0]a[2][1]a[2][2]
  • The elements are stored in a sequential manner with all the elements of a row together one below the other, and then the next row and so on
  • The method of accepting elements of an m x n matrix and displaying it in natural form is (m is the number of rows and n is the number of columns)
  • The values of the variable are taken from the user
  • C provides rectangular multi-dimensional arrays, although in practice they are much less used than arrays of pointers
  • The correspondence between indexing and pointer arithmetic is very close. by definition, the value of a variable or expression of type array is the address of element zero of the array

ADD two matrix using 2-D array

#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,i,j,a[10][10],b[10][10],c[10][10];
clrscr();
printf("Enter the number of rows and columns:");
scanf("%d%d",&m,&n);
printf("Enter the element of matrix 1\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter the value");
scanf("%d",&a[i][j]);
}
}
printf("enter the element of matrix 2\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter the value:");
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("the sum of two matrices is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}

OUTPUT:
Enter the number of rows and columns:2
3
Enter the element of matrix 1
enter the value:1
enter the value:2
enter the value:3
enter the value:4
enter the value:5
enter the value:6
enter the element of matrix 2
enter the value:1
enter the value:2
enter the value:3
enter the value:4
enter the value:5
enter the value:6
the sum of two matrices is:
2    4    6
8   10   12

Explanation for the above Program of ADDING of TWO MATRICES:

  • The method to accept the elements of the matrix is the same as the previous program
  • The corresponding elements of the matrices “a” and “b” are added together and the result is put into the matrix “c”
  • The elements of matrices “a” and matrices “b” of the same index were added in this program and thus passed to the C
  • This “c” matrix is then displayed in natural form
Translate »