Skip to content
Home » C program to add two matrices

C program to add two matrices

Below is the program to add two matrices.

#include <stdio.h>
int main(){
    int a,b,c,d;
    printf("Enter number of rows in first matrix:\n");
    printf("Enter number of columns in first matrix:\n");
    printf("Enter number of rows in second matrix:\n");
    printf("Enter number of columns in second matrix:\n");
    scanf("%d %d %d %d",&a,&b,&c,&d);
    int m1[a][b];
    int m2[c][d];
    printf("Enter elements of first matrix:\n");
    int i,j;
    for(i=0;i<a;i++){
        for(j=0;j<b;j++){
            scanf("%d",&m1[i][j]);
        }
    }
    printf("Enter elements of second matrix:\n");
    int x,y;
    for(x=0;x<c;x++){
        for(y=0;y<d;y++){
            scanf("%d",&m2[x][y]);
        }
    }
    if(a==c && b==d){
        printf("Matrix addition is possible\n");
    }
    else{
        printf("Matrix addition is not possible\n");
    }
    int m3[a][b];
    for(i=0;i<a;i++){
        for(j=0;j<b;j++){
            m3[i][j]=m1[i][j]+m2[i][j];
            
        }
    }
    for(i=0;i<a;i++){
        for(j=0;j<b;j++){
            printf("%d    ",m3[i][j]);
        
        }
    printf("\n\n");
    }
    return 0;
}

Output 1:


Enter number of rows in first matrix:
Enter number of columns in first matrix:
Enter number of rows in second matrix:
Enter number of columns in second matrix:
2
2
2
2
Enter elements of first matrix:
4
3
5
2
Enter elements of second matrix:
5
3
4
7
Matrix addition is possible
9 6

9 9