Multiplication of two 3x3 matrices in C

I am trying to multiply two 3x3 matrices. The first 2 numbers in the first and second lines are the only correct answer. What am I doing wrong? Is the material I need in mult_matrices?

#include <stdio.h>

void mult_matrices(int a[][3], int b[][3], int result[][3]);
void print_matrix(int a[][3]);

int main()
{
    int p[3][3] = {{1, 2, 3},{4, 5, 6}, {7, 8, 9}};
    int q[3][3] = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}};
    int r[3][3];

    mult_matrices(p, q, r);
    print_matrix(r);
}

void mult_matrices(int a[][3], int b[][3], int result[][3])
{
    int i, j, k;
    for(i = 0; i < 3; i++)
    {
            for(j = 0; j < 3; j++)
            {
                    for(k = 0; k < 3; k++)
                    {
                            result[i][j] +=  a[i][k] *  b[k][j];
                    }
            }
    }
}

void print_matrix(int a[][3])
{
    int i, j;
    for (i = 0; i < 3; i++)
    {
            for(j = 0; j < 3; j++)
            {
                    printf("%d\t", a[i][j]);
            }
            printf("\n");
    }
 }
+5
source share
4 answers

It looks like you are not initializing your matrix result.

i.e. Change:

int r[3][3];

to

int r[3][3] ={{0,0,0},{0,0,0},{0,0,0}};
+7
source

Make sure you initialize rto all zeros before using it.

int r[3][3] = { 0 };
+8
source

, , , - r [3] [3]. , , . , , r, - , "" . 0, , , . , , , .

+4
source
int main(){ 
  int A[3][3],B[3][3],C[3][3],i,j; 
  printf("Please Enter 9 Numbers for First Matrix") 
  for(i=0;i<=2;i++){
    for(j=0;j<=2;j++){ 
      scanf("%d",A[i][j]);
    }
  }
  printf("Please Enter 9 Numbers for Second Matrix") 
  for(i=0;i<=2;i++){ 
    for(j=0;j<=2;j++){ 
      scanf("%d",B[i][j]); 
    }
  } 
  for(i=0;i<=2;i++){ 
    for(j=0;j<=2;j++){ 
      C[i][j]=A[i][j]+B[i][j] 
      printf("%d "C[i][j]); 
    } 
    printf("\n");
  }
}
+1
source

All Articles