5x5 matrix multiplication in C
Posted
by Rick
on Stack Overflow
See other posts from Stack Overflow
or by Rick
Published on 2010-03-15T01:49:33Z
Indexed on
2010/03/15
1:59 UTC
Read the original article
Hit count: 678
I am stuck on this problem in my homework. I've made it this far and am sure the problem is in my three for loops. The question directly says to use 3 for loops so I know this is probably just a logic error.
#include<stdio.h>
void matMult(int A[][5],int B[][5],int C[][5]);
int printMat_5x5(int A[5][5]);
int main() {
int A[5][5] = {{1,2,3,4,6},
{6,1,5,3,8},
{2,6,4,9,9},
{1,3,8,3,4},
{5,7,8,2,5}};
int B[5][5] = {{3,5,0,8,7},
{2,2,4,8,3},
{0,2,5,1,2},
{1,4,0,5,1},
{3,4,8,2,3}};
int C[5][5] = {0};
matMult(A,B,C);
printMat_5x5(A);
printf("\n");
printMat_5x5(B);
printf("\n");
printMat_5x5(C);
return 0;
}
void matMult(int A[][5], int B[][5], int C[][5])
{
int i;
int j;
int k;
for(i = 0; i <= 2; i++) {
for(j = 0; j <= 4; j++) {
for(k = 0; k <= 3; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
int printMat_5x5(int A[5][5]){
int i;
int j;
for (i = 0;i < 5;i++) {
for(j = 0;j < 5;j++) {
printf("%2d",A[i][j]);
}
printf("\n");
}
}
EDIT: Here is the question, sorry for not posting it the first time.
(2) Write a C function to multiply two five by five matrices. The prototype should read
void matMult(int a[][5],int b[][5],int c[][5]);
The resulting matrix product (a times b) is returned in the two dimensional array c (the third parameter of the function). Program your solution using three nested for loops (each generating the counter values 0, 1, 2, 3, 4) That is, DO NOT code specific formulas for the 5 by 5 case in the problem, but make your code general so it can be easily changed to compute the product of larger square matrices. Write a main program to test your function using the arrays
a:
1 2 3 4 6
6 1 5 3 8
2 6 4 9 9
1 3 8 3 4
5 7 8 2 5
b:
3 5 0 8 7
2 2 4 8 3
0 2 5 1 2
1 4 0 5 1
3 4 8 2 3
Print your matrices in a neat format using a C function created for printing five by five matrices. Print all three matrices. Generate your test arrays in your main program using the C array initialization feature.
enter code here
© Stack Overflow or respective owner