To multiply two Matrices

Here is the program to find the product of the two integer matrices. The program asks for the order A (M, N) of the first matrix, and that B (P, Q) of the second matrix.  Soon after entering the order, the cursor takes to the proper position in the screen to input the matrices. User need to hit ‘Enter’ button after each entry.

Logic : To multiply two matrices, the condition should be satisfy that the column count of the  first matrix A should equal the column count of the second matrix B. (The program will check for the validity of this condition i.e. if, N = P. If fails, outputs an error message.) The first row of A is multiplied with with the first column of B. i.e. the first member of the first row of A is multiplied with the first member of first column of B, stored in a variable sum, second with the second and the product is added up, similarly, the procedure grows till the end, and sum is updated in each multiply, and the sum will be the first member of the product matrix C. The procedure grows till the end. Finally we will get the product matrix C of order (M, Q).

The procedure can be modified slightly with the same algorithm, to add,  subtract,  transpose or others like, to trace the diagonals etc.

#include<stdio.h>
void main()
{
int A[5][5],B[5][5],C[5][5],i,j,m,n,p,q,k;
clrscr();
printf(“\n\n\t ENTER A ORDER OF THE FIRST MATRIX M,N…: “);
scanf(“%d,%d”,&m,&n);
printf(“\n\n\t ENTER A ORDER OF THE SECOND MATRIX P,Q…: “);
scanf(“%d,%d”,&p,&q);
if(n == p)
{
printf(“\n\n\t ENTER THE ELEMENTS OF THE FIRST MATRIX..:\n\n”);
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
gotoxy(25+j*4,14+i*2);
scanf(“%d”,&A[i][j]);
}
printf(“\n”);
}
printf(“\n\t ENTER THE ELEMENTS OF THE SECOND MATRIX..:\n\n”);
for(i=1;i<=p;i++)
{
for(j=1;j<=q;j++)
{
gotoxy(25+j*4,20+m+i*2);
scanf(“%d”,&B[i][j]);
}
printf(“\n”);
}
for(i=1;i<=m;i++)
for(j=1;j<=q;j++)
{
C[i][j] = 0;
for(k=1;k<=n;k++)
C[i][j] = C[i][j] + (A[i][k] * B[k][j]);
}
printf(“\n\t THE PRODUCT OF TWO MATRICES IS…:\n\n\t\t\t “);
for(i=1;i<=m;i++)
{
for(j=1;j<=q;j++)
printf(” %d”,C[i][j]);
printf(“\n\n\t\t\t “);
}
}
else
{
printf(“\n\t THE ORDERS OF TWO MATRICES ARE NOT CORRECT”);
printf(“\n\n\t HELP : ‘N’ SHOULD BE EQUAL TO ‘P'”);
}
getch();
}
Download exe and source code here.

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in