Chetan Pujar - 2 months ago 6x
C Question

# A C program meant to find the product of matrices isn't working

The lines of codes that come after the input of the elements of the matrix 'b' are not being executed. Also the nothing happens on pressing the enter button.
I wanted t know if this is a logic error or a semantic error.

``````#include<stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m1,m2,n1,n2;
printf("Enter the order of the matrix a: ");
scanf("%d%d",&m1,&n1);
printf("Enter the order of the matrix b: ");
scanf("%d%d",&m2,&n2);
//test for eligibility of matrices for multiplication
if(n1==m2)
{
//input of the elements of matrix a
printf("Enter the elements of the matrix a: ");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
scanf("%d",&a[i][j]);
}
//Input of the elements of the matrix b
printf("Enter the elements of the matrix b: ");
for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
scanf("%d",&b[i][j]);
}
//calculating the result of multiplication of matrices 'a' and 'b'
printf("The result of multiplication of 'a' and 'b' is: ");
for(i=0;i<n1;i++)
{
for(j=0;j<m2;j++)
{
for(k=0;k<n2;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
scanf("%d",&c[i][j]);
}
}
}
//print the resultant matrix
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
printf("%4d",c[i][j]);
}
}
}
else
printf("The matrices are not eligible for multiplication");
}
``````

Okay, I took the time to fix it up:

``````#include <stdio.h>
#include <string.h> // New, for memset()

int main(void) // "Proper" signature
{
int a[10][10],b[10][10],c[10][10],i,j,k,m1,m2,n1,n2;
memset(c, 0, 100); // New, Ug Lee way of zeroing of the array
printf("Enter the order of the matrix a: ");
scanf("%d%d",&m1,&n1);
printf("Enter the order of the matrix b: ");
scanf("%d%d",&m2,&n2);
//test for eligibility of matrices for multiplication
if(n1==m2)
{
//input of the elements of matrix a
printf("Enter the elements of the matrix a: ");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
scanf("%d",&a[i][j]);
}
//Input of the elements of the matrix b
printf("Enter the elements of the matrix b: ");
for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
scanf("%d",&b[i][j]);
}
//calculating the result of multiplication of matrices 'a' and 'b'
printf("The result of multiplication of 'a' and 'b' is: \n");
for(i=0;i<n1;i++)
{
for(j=0;j<m2;j++)
{
for(k=0;k<n2;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
// scanf removed
}
}
}
//print the resultant matrix
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
printf("%4d ",c[i][j]);
}
The algorithm itself is fundamentally good. Your next step is to improve the code to use `calloc` for array allocation for the exact size you need for the matrices.