C/matrices
Expert: Narendra - 7/13/2006
QuestionI've been working on this all week and I still can't figure it out. I'm having problems writing the code for mulitipling matries and printing out the results. Here are my two functions for those parts can you please help me correct it.
void multiplymatrices(int d[][50], int e[][50], int f[][50], int s1, int s2, int s3, int s4)
{
int g;
int h;
int i;
if((s2 == s3)){
for( g=0; g<s1; g++)
for( h=0; h<s2; h++)
for(i=0; i<s2; i++)
f[g][i]+= d[g][h]*e[h][i];
}
else
printf("Multiplication not possible\n");
}
void printresults(int g[][50], int SI1, int SI2, int SI3, int SI4)
{
int h;
int i;
for (h = 0; h < SI1; h++)
for( i = 0; i < SI2; i++)
printf("%d %d", h, i);
}
AnswerHere is a program which does the same thing.
Only difference is, I am not passing array to functions.
Arrays get converted to pointers when sent as parameters to functions and it is a bit tricky to make it work then.
Anyway the following program should work for you:
#include <stdio.h>
int mat1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int mat2[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int result[50][50] = {0};
void multiplymatrices()
{
int g;
int h;
int i;
for (g = 0; g < 3; g++)
for (h = 0; h < 3; h++)
{
int sum = 0;
for (i = 0; i < 3; i++)
{
sum = sum + (mat1[g][i] * mat2[i][h]);
}
result[g][h] = sum;
}
}
void printresults()
{
int i;
int j;
for( i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
printf("%d ", result[i][j]);
printf("\n");
}
}
main()
{
multiplymatrices();
printresults();
}