C PROGRAM MATRIX MULTIPLICATION CODE WITH EXAMPLE

We can only multiply matrices if the number of columns in the first matrix is the same as the number of rows in the second matrix. We multiply and add the elements as follows.

1st row of the first matrix, multiplying down the 1st column of the second matrix, element by element. We add the resulting products. Our answer goes in position a11 (top left) of the answer matrix.

 

#include <stdio.h> 

#define ROWS1 2
#define COLS1 4

#define ROWS2 4
#define COLS2 3

int main() 
{ 

int mat1[ROWS1][COLS1],mat2[ROWS2][COLS2],mat3[ROWS1][COLS2]; 
int r,c,k; 

if(COLS1==ROWS2)
{

printf("Pl. Enter Matrix 1 elements :----------\n");
//Read Matrix 1
for (r = 0; r < ROWS1; r++) 
{ 
   for(c = 0; c < COLS1; c++) 
   { 
         printf("\nENTER VALUE AT mat1[%d][%d] : ", r, c); 
         scanf("%d", &mat1[r][c]); 
   } 
} 

printf("Ok, Now Enter Matrix 2 elements :----------\n");
//Read Matrix 2
for (r = 0; r < ROWS2; r++) 
{ 
   for(c = 0; c < COLS2; c++) 
   { 
         printf("\nENTER VALUE AT mat2[%d][%d] : ", r, c); 
         scanf("%d", &mat2[r][c]); 
   } 
} 

printf("Ok, Now Enter Matrix 2 elements :----------\n");

//matrix multiplication
for (r = 0; r < ROWS1; r++) 
{
   
   for(c = 0; c < COLS2; c++) 
   { 
         mat3[r][c]=0; 
         for(k=0;k<COLS1;k++)
	 {
		mat3[r][c]=mat3[r][c]+mat1[r][k]*mat2[k][c];
	 } 
         
   } 
   
} 


printf("\nMATRIX-1 : \n\n"); 
for (r = 0; r < ROWS1; r++) 
{ 

   for(c = 0; c < COLS1; c++) 
   {
         printf("%d ",mat1[r][c]); 
   } 
   printf("\n");
} 


printf("\nMATRIX-2: \n\n"); 
for (r = 0; r < ROWS2; r++) 
{ 

   for(c = 0; c < COLS2; c++) 
   {
         printf("%d ",mat2[r][c]); 
   } 
   printf("\n");
} 

printf("\nMATRIX MULTIPLICATION IS : \n\n"); 
for (r = 0; r < ROWS1; r++) 
{ 

   for(c = 0; c < COLS2; c++) 
   {
         printf("%d ",mat3[r][c]); 
   } 
   printf("\n");
} 
}
else
{
	printf("\n SORRY! MATRIX MULTIPLICATION CONDITION NOT SATISFIED..\n (COLUMNS OF FIRST MATRIX MUST BE EQUAL TO ROWS OF SECOND MATRIX)\n");
}
return 0;

}

Download Code:  matrix-multiplication.c (103 downloads)

Output

output-matrix-multiplication
output-matrix-multiplication