Multiplying and adding two matrices

This is a C example which demonstrates how to multiply and add two matrices. 

You can compile this program on bOtskOOl Free Online C/C++ Compiler

 

// A C program to multiply and add 2 matrices
 
 
/*
**********************
www.botskool.com
**********************
*/
 
#include<stdio.h>
#include<conio.h>
 
void main()
{
int i,j,m,n,p,q,k,l;
int a[10][10],b[10][10],prod[10][10],sum[10][10];
clrscr();
 
//input first matrix
printf("\nEnter dimensions for first matrix: (mxn)");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
 {
    for(j=0;j<n;j++)
                {
                printf("Enter the element (%d,%d) ",i+1,j+1);
                scanf("%d",&a[i][j]);
                }
 }
//input second matrix
printf("\nEnter dimensions for second matrix: (pxq)");
scanf("%d%d",&p,&q);
for(i=0;i<p;i++)
 {
    for(j=0;j<q;j++)
                {
                printf("Enter the element (%d,%d) ",i+1,j+1);
                scanf("%d",&b[i][j]);
                }
 }
clrscr();
printf("\n Matrix A\n");
display(a,m,n);
printf("\n Matrix B\n");
display(b,p,q);
 
 
//check and multiply
if(n==p)
 {
 for(i=0;i<m;i++)
    {
                for(j=0;j<q;j++)
                                {prod[i][j]=0;
                                for(l=0;l<n;l++)
                                prod[i][j]+=a[i][l]*b[l][j];
                                }
    }
 printf("\n AXB\n");
 display(prod,m,q);
 }
else
{
printf("\n ---!MULTIPLICATION NOT POSSIBLE!---");
}
 
 
//check and add
if(m==p&&n==q)
 {for(i=0;i<m;i++)
    {
                for(j=0;j<n;j++)
                 sum[i][j]=a[i][j]+b[i][j];
    }
   printf("\n A+B\n");
   display(sum,m,q);
 }
else
 {
   printf("\n ---!ADDITTION NOT POSSIBLE!---");
 }
 
 
 
 
 
getch();
}
 
display(int *ar,int m,int n)
{int i,j;
printf("\n");
for(i=0;i<m;i++)
 {
                for(j=0;j<n;j++)
                printf(" %3d ",*(ar+i*10+j));
printf("\n");
 }
return 0;
 
}
 
/*
**********************
www.botskool.com
**********************
*/

 

Output will be like this:-

Output - Multiplying and adding two matrices

 

Download source code.

 

 

Terms of Agreement:  
By using this code, you agree to the following terms-  
1) You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.  
2) You MAY NOT redistribute this code (for example to a web site) without written permission from us. Failure to do so is a violation of copyright laws.  
3) You may link to this code from another website, but ONLY if it is not wrapped in a frame.
4) You will abide by any additional copyright restrictions which may have placed in the code or code's description.
>>Kindly post your doubts and suggestions on our discussion forum.
Tags: