Two Dimensional Array

Two Dimensional Array:

  • It is nothing but array of array.
  • syntax : data_type arr_name[num_of_rows][num_of_column];
    Array declaration, initialization and accessing in c Examples
    Array declaration syntax:data_type array_name [num_of_rows][num_of_column];Array initialization syntax:data_type array_name[2][2] = {{0,0},{0,1},{1,0},{1,1}}; Array accessing syntax: array_name[index];array_name[index]; Integer array example:int arr1[2][2];int arr1[2][2] = {1,2, 3, 4};arr1 [0] [0] = 1;arr1 [0] ]1] = 2;

    arr1 [1][0] = 3;

    arr1 [1] [1] = 4;

 

Example 1

#include

int main()

{

int i1,j1; // declaring and Initializing array

int arr1[2][2] = {10,20,30,40}; /* Above array can be initialized as below also

arr1[0][0] = 10; // Initializing array

arr2[0][1] = 20;

arr3[1][0] = 30;

arr4[1][1] = 40; */

for (i1=0;i1<2;i1++)

{

for (j1=0;j1<2;j1++)

{

// Accessing variables

printf(“value of arr1[%d] [%d] : %d\n”,i1,j1,arr1[i1][j1]);

}

}

return 0;

}

Output

value of arr1[0] [0] is 10

value of arr1[0] [1] is 20

value of arr1[1] [0] is 30

value of arr1[1] [1] is 40

WAP to find Sum of two matrices using Two dimensional arrays WAP to find the sum of two matrices of order 2*2 using two dimensional arrays

#include<stdio.h>

int main()

{

float a1[2][2], b1[2][2], c1[2][2];

int i1, j1;

// Taking input using nested for loop

printf(“Enter elements of firstst matrix\n”);

for(i1=0; i1<2; ++i1)

for(j1=0; j1<2; ++j1)

{

printf(“Enter a%d%d: “, i1+1, j1+1);

scanf(“%f”, &a1[i1][j1]); } // Taking input using nested for loop printf(“Enter elements of 2nd matrix\n”);

for(i1=0; i1<2; ++i1)

for(j1=0; j1<2; ++j1)

{

printf(“Enter b%d%d: “, i1+1, j1+1);

scanf(“%f”, &b1[i1][j1]); } // adding corresponding elements of two arrays

for(i1=0; i1<2; ++i1)

for(j1=0; j1<2; ++j1)

{

C1[i1][j1] = a1[i1][j1] + b1[i1][j1]; } // Displaying the sum

printf(“\nSum Of Matrix:”);

for(i1=0; i1<2; ++i1)

for(j1=0; j1<2; ++j1)

{

printf(“%.1f\t”, c1[i1][j1]);

if(j1==1) printf(“\n”);

}

return 0;

}

Output

Enter elements of firstst matrix

Enter a11: 12; Enter a12: 34;

Enter a21: 46;

Enter a22: 56;

Enter elements of 2nd matrix

Enter b11: 67;

Enter b12: 78;

Enter b21: 67;

Enter b22: 67;

Sum Of Matrix:

79.0 112.0

113.0 123.0

Leave a Reply

Your email address will not be published. Required fields are marked *