C Addition of two matrices


 

C Addition of two matrices

In this section, we are going to calculate the sum of two 2 X 2 matrices containing rows and columns.

In this section, we are going to calculate the sum of two 2 X 2 matrices containing rows and columns.

C Addition of two matrices

In this section, we are going to calculate the sum of  two 2 X 2 matrices containing rows and columns. For this , we need to declare two dimensional array of integer type. Here, we prompt  the user to input values for two matrices. To make the matrix of 2 X 2, we are using for loop. By the use of for loop, the values will get arrange in rows and columns. After getting both the matrix, the matrices will be added by using the for loop with a[i][j]+b[i][j].

Here is the code:

#include <stdio.h>

void main() {
     int a[2][2], b[2][2], c[2][2], i, j;
     clrscr();
     printf("Enter the First matrix:\n");
     for (i = 0; i < 2; i++) {
              for (j = 0; j < 2; j++) {
                  scanf("%d", &a[i][j]);
              }
     }
     printf("\nThe First matrix is:\n");
     for (i = 0; i < 2; i++) {
           printf("\n");
          for (j = 0; j < 2; j++)
          printf("%d\t", a[i][j]);
     }
     printf("\nEnter the Second matrix:\n");
     for (i = 0; i < 2; i++) {
          for (j = 0; j < 2; j++) {
                   scanf("%d", &b[i][j]);
          }
     }
     printf("\nThe Second matrix is:\n");
     for (i = 0; i < 2; i++) {
            printf("\n");
            for (j = 0; j < 2; j++)
            printf("%d\t", b[i][j]);
     }
     for (i = 0; i < 2; i++)
           for (j = 0; j < 2; j++)
           c[i][j] = a[i][j] + b[i][j];
            printf("\nThe Addition of two matrix is:\n");
     for (i = 0; i < 2; i++) {
          printf("\n");
          for (j = 0; j < 2; j++)
          printf("%d\t", c[i][j]);
     }
getch();
}

Output

Enter the First matrix:
1
2
3
4
The First matrix is:
1         2
3         4
Enter the Second matrix:
5
6
7
8
The Second matrix is:
5         6
7         8
The Addition of two matrix is:
6         8
10       12

Ads