Thursday, July 14, 2011

C Program to Add Two Matrices using 2D Array


As a C Programmer ,you need to deal with data structures likes an array.Programmers often needs to use a Multidimensional array in the form of matrix to do mathematical Calculations.The Program below Demonstrates the addition of any  two user specified matrices together and obtain the result in a new Matrix.
The Complete Source Code to implement matrix addition  by using 2D Integer Array is given Below.

 #include<stdio.h>  
 #include<conio.h>  
 void main()  
 {  
  int A[50][50],B[50][50],C[50][50];  
  int i,j,r1,r2,c1,c2;  
  clrscr();  
  printf("   * Matrix Addition*     ");  
  printf("\nEnter The Size Of First Matrix:");  
  scanf("%d%d",&r1,&c1);  
  printf("\nEnter The Elements Of First Matrix:");  
  for(i=0;i<r1;i++)  
  for(j=0;j<c1;j++)  
  scanf("%d",&A[i][j]);  
  printf("\n\nEnter The Size Of Second Matrix:");  
  scanf("%d%d",&r2,&c2);  
  printf("\nEnter The Elements Of Second Matrix:");  
  for(i=0;i<r2;i++)  
   for(j=0;j<c2;j++)  
     scanf("%d",&B[i][j]);  
  if(r1!=r2||c1!=c2)  
  {  
   printf("\n\nThe Matrix Cant Be Added!!!");  
   getch();  
   exit(0);  
  }  
  for(i=0;i<r1;i++)  
   for(j=0;j<c1;j++)  
     C[i][j]=A[i][j]+B[i][j];  
  printf("\n\nThe Sum Of Matrices Is:");  
  for(i=0;i<r1;i++)  
  { printf("\n");  
    for(j=0;j<c1;j++)  
     printf("%d ",C[i][j]);  
  }  
  getch();  
 }  

1 comments:

  • toki master says:
    January 5, 2014 at 4:41 AM

    Hi.
    Is it possible in 2d array that we can add two arrays with different Rows and Cols.
    e.g.
    A[6][6] + B[3][3]

Post a Comment

Subscribe

The Source Codes Published in this Blog can be used freely for Educational purposes but should not be reproduced on any other Blog or Website without the consent of the author.