Program to add two matrices using functions 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");
       print_matrix(c);
 
       /*Print the matrix d*/
       printf("nThe matrix d as entered is...n");
       print_matrix(d);
 
       /*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");
              print_matrix(e);
        return 0;
        }
 
        print_matrix(int x[][])
        {
              int i, j;
              for(i=0;i<M;i++){
                  for(j=0;j<N;j++)
                      printf("%4d",x[i][j]);
                  printf("n");
 }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.