Multiplying two 3x3 matrices in C

14,249

Solution 1

Looks like you're not initializing your result matrix.

i.e. Change:

int r[3][3];

to

int r[3][3] ={{0,0,0},{0,0,0},{0,0,0}};

Solution 2

Make sure you initialize r to all zeros before you use it.

int r[3][3] = { 0 };

Solution 3

One thing that I notice that you don't do is initialize you're r[3][3] array. I am not sure if this is the root of you're problem but it very well could be. Essentially what the values of r are set to is whatever was "left over" in memory in that location. Sometimes they will all be 0 but most likely they will not be. So it could be the issue you are having, but even if it isn't it is good to always get in a habit of initializing all of you're variables.

Solution 4

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");
  }
}
Share:
14,249
james
Author by

james

Updated on June 09, 2022

Comments

  • james
    james almost 2 years

    I am trying to multiply two 3x3 matrices. The first 2 numbers in the first and second row are the only correct answer. What am I doing wrong? Is the stuff I need declared 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");
        }
     }
    
  • james
    james about 13 years
    @yan.. It's still now right I get as my answer. {19 20 21, 22 23 24, 25 26 27}
  • james
    james about 13 years
    @james sorry! I was making a logical error. it's working Now! Thanks a bunch