Trying to make 3 x 3 matrix multiplier but it gives out wrong output. I don’t know what I am doing wrong. Two problems that I am facing are:
(1) Some variables store wrong input. For example a[1][1] shows 7 although I entered 1
(2) The matrix multiplication is wrong
#include <stdio.h>
#include <conio.h>
void matrix_format(int m[2][2])
{
int i,j;
printf("\n\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
if(j==0)
printf("[ %d |",m[i][j]);
else if(j==1)
printf(" %d |",m[i][j]);
else if(j==2)
printf(" %d ] \n",m[i][j]);
}
}
}
int main(void)
{
void matrix_format(int [2][2]);
int a[2][2], b[2][2], r[2][2],m,i,j;
clrscr();
for(m=1;m<=2;m++)
{
if(m==1)
{
printf("Enter values for the matrix A \n");
}
else
{
printf("\n\nEnter values for the matrix B \n");
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
if(m==1)
{
printf("A[%d][%d] : ",i+1,j+1);
scanf("%d",&a[i][j]);
}
else if(m==2)
{
printf("B[%d][%d] : ",i+1,j+1);
scanf("%d",&b[i][j]);
}
}
}
}
printf("\n Matrix A : \n");
matrix_format(a);
printf("\n Matrix B : \n");
matrix_format(b);
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
r[i][j]= a[i][j] * b[j][i];
}
}
printf("\n Matrix Multiplication Result : \n");
matrix_format(r);
getch();
return 0;
}
output:


Please guide me.
The first problem that jumps out is that all your arrays are 2×2, while they should be 3×3:
should read
and so on. The number in brackets is the size of the array, not the index of the last element.
This will explain some of the weirdness, in particular why some elements get mysteriously overwritten.
As to the actual matrix multiplication, your algorithm isn’t quite right (assuming what you’re trying to implement is the standard linear algebra matrix product). Think about what steps are involved in multiplying two matrices, and what your code is actually doing. Since this is homework, I’ll only give you a hint: