C Programming : C Programming Source Code to add two matrices

Below is C Programming Source Code to add two matrices.

Algorithm

Accept two matrices using for loop
Check the size of the two matrices
If their size is the same, add them else display error massage.

Code

#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
  int r1, c1,r2,c2, i, j, A[10][10], B[10][10], sum[10][10];
  printf("Enter the number of rows of the first matrix\n"wink;
  scanf("%d", &r1);
  printf("Enter the number of columns of the first matrix\n"wink;
  scanf("%d",&c1);
  printf("Enter the elements of first matrix\n"wink;
  for (i = 0 ; i < r1 ; i++)
     for (j = 0 ; j < c1 ; j++)
scanf("%d", &A[i][j]);
printf("The first matrix\n"wink;
printf("================\n"wink;
  for (i = 0 ; i < r1 ; i++){
     for (j = 0 ; j < c1 ; j++)
printf("%d\t", A[i][j]);
     printf("\n"wink;
  }
printf("\nEnter the number of rows of the second matrix\n"wink;
  scanf("%d", &r2);
  printf("Enter the number of columns of the second matrix\n"wink;
  scanf("%d",&c2);
  printf("Enter the elements of second matrix\n"wink;
 for (i = 0 ; i < r2 ; i++)
     for (j = 0 ; j < c2 ; j++)
   scanf("%d", &B[i][j]);
printf("The second matrix\n"wink;
printf("================\n"wink;
  for (i = 0 ; i < r2 ; i++){
     for (j = 0 ; j < c2 ; j++)
printf("%d\t", B[i][j]);
     printf("\n"wink;
  }
   if(r1==r2 && c1==c2){
  for (i = 0 ; i < r1 ; i++)
     for (j = 0 ; j < c1 ; j++)
sum[i][j] = A[i][j] + B[i][j];
  printf("Sum of the two matrices\n"wink;
  printf("=======================\n"wink;
  for (i = 0 ; i < r1 ; i++){
     for (j = 0 ; j < c1 ; j++)
printf("%d\t", sum[i][j]);
     printf("\n"wink;
  }
}
  else
  printf("\nError! Size of matrices do not agree and hence can not be addeded."wink;
  getch();
}
Posted by makeale 01/05/2015 03:17 PM Comments
 

Archives