Matrix addition and subtraction in C using arrays

On : 10:49 AM

Consider 4 matrices, A, B,C and D, we are going to add A and B and keep on C. (A+B = C). And will subtract B from A and keep it on D.(A-B=D).

First we need to check that the number of rows of matrix A is equal to the number of rows of matrix B, Also we should perform the same check in case of column. But in our program we assume that number of rows of A and B are equal, as well as the column of A is equal to column of B. Then we goes

c[00]=a[00]+b[00], c[01]=a[01]+b[01]… and so on.
d[00]=a[00]-b[00], c[01]=a[01]-b[01]… and so on.

Lets coding this simple Program.


#include<stdio.h>

int main(){
    int a[10][10],b[10][10],c[10][10],d[10][10], row, col,i,j;

    printf("Enter the rows number of both matrices\n");
    scanf("%d",&row);
    printf("Enter the columns number of both matrices\n");
    scanf("%d",&col);


        printf("Enter the elements of matrix A\n");
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                printf("Enter the element at [%d%d] : ",i,j);
                scanf("%d",&a[i][j]);
            }
            printf("\n");

        }

        printf("Enter the elements of matrix B\n");
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                printf("Enter the element at [%d%d] : ",i,j);
                scanf("%d",&b[i][j]);
            }
            printf("\n");

        }

        printf("The addition of A and B is \n\t\t");
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                c[i][j]=a[i][j] + b[i][j];
            }
        }
        //printing addition
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                printf(" %d ",c[i][j]);
            }
            printf("\n\t\t");
        }


        printf("\nThe subtraction of A and B is \n\t\t");
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                d[i][j]=a[i][j] - b[i][j];
            }
        }

        //printing subtraction
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                printf(" %d ",d[i][j]);
            }
            printf("\n\t\t");
        }



    return 0;
}