Program to add two matrices in C

#include <stdio.h>
 
 int main()
 {
    const int M=3,N=3;  // M holds no of rows, N holds no of cols
    int c[M][N],d[M][N],e[M][N];
    int i, j;
 
    /*Read in the values for the c and d matrices*/
    printf("nEnter the elements of matrices c and d row-wise");
    printf("nIn the format c[i][j],d[i][j]...n");
    for(i=0;i<M;i++)
        for(j=0;j<N;j++)
            scanf("%d,%d",&c[i][j],&d[i][j]);
 
    /*Print the matrix c*/
    printf("nThe matrix c as entered is...n");
    for(i=0;i<M;i++)
    {
        for(j=0;j<N;j++)
            printf("%4d",c[i][j]);
        printf("n");
    }
 
    /*Print the matrix d*/
    printf("nThe matrix d as entered is...n");
    for(i=0;i<M;i++)
    {
        for(j=0;j<N;j++)
            printf("%4d",d[i][j]);
        printf("n");
    }
 
    /*Calculate the sum of the two matrices into matrix e*/
    for(i=0;i<M;i++)
        for(j=0;j<N;j++)
           e[i][j]=c[i][j]+d[i][j];
 
    /*Print the result matrix e*/
    printf("nThe matrix e as a sum of c and d is...n");
    for(i=0;i<M;i++)
    {
        for(j=0;j<N;j++)
            printf("%4d",e[i][j]);
        printf("n");
    }
    return 0;
 }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.