Matrix multiplication in C

Matrix multiplication in C: We can add, subtract, multiply and divide 2 matrices. To do so, we are taking input from the user for row number, column number, first matrix elements and second matrix elements. Then we are performing multiplication on the matrices entered by the user.
In matrix multiplication first matrix one row element is multiplied by second matrix all column elements.
Let's try to understand the matrix multiplication of 2*2 and 3*3 matrices by the figure given below:
matrix multiplication program in c
Let's see the program of matrix multiplication in   c

  1. #Using 2D array
  2. #include<stdio.h>  
  3. int main(){  
  4. int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;    
  5. printf("enter the number of row=");    
  6. scanf("%d",&r);    
  7. printf("enter the number of column=");    
  8. scanf("%d",&c);    
  9. printf("enter the first matrix element=\n");    
  10. for(i=0;i<r;i++)    
  11. {    
  12. for(j=0;j<c;j++)    
  13. {    
  14. scanf("%d",&a[i][j]);    
  15. }    
  16. }    
  17. printf("enter the second matrix element=\n");    
  18. for(i=0;i<r;i++)    
  19. {    
  20. for(j=0;j<c;j++)    
  21. {    
  22. scanf("%d",&b[i][j]);    
  23. }    
  24. }    
  25.     
  26. printf("multiply of the matrix=\n");    
  27. for(i=0;i<r;i++)    
  28. {    
  29. for(j=0;j<c;j++)    
  30. {    
  31. mul[i][j]=0;    
  32. for(k=0;k<c;k++)    
  33. {    
  34. mul[i][j]+=a[i][k]*b[k][j];    
  35. }    
  36. }    
  37. }    
  38. //for printing result    
  39. for(i=0;i<r;i++)    
  40. {    
  41. for(j=0;j<c;j++)    
  42. {    
  43. printf("%d\t",mul[i][j]);    
  44. }    
  45. printf("\n");    
  46. }    
  47. return 0;  
  48. }  

  1. Using 3D array:

    #include<stdio.h>    
    int main()
    {  
    int a[10][10][10],r,c,i,j,k,l;   
    printf("enter the number of row="); 
    scanf("%d",&r);    
    printf("enter the number of column=");    
    scanf("%d",&c);
    for(k=0;k<2;k++) {

    printf("enter the  matrix(%d) element=\n",k+1);    
    for(i=0;i<r;i++)    
    {    
    for(j=0;j<c;j++)    
    {    
    scanf("%d",&a[k][i][j]);    
    }    
    }}    

    printf("multiply of the matrix=\n");    
    for(i=0;i<r;i++)    
    {    
    for(j=0;j<c;j++)    
    {    
    a[2][i][j]=0;    
    for(l=0;l<c;l++)    
    {    
    a[2][i][j]+=a[0][i][l]*a[1][l][j];    
    }    
    }    
    }    
    //for printing result    
    for(i=0;i<r;i++)    
    {    
    for(j=0;j<c;j++)    
    {    
    printf("%d\t",a[2][i][j]);    
    }    
    printf("\n");    
    }    
    return 0;  
    }  

Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
1 1 1
2 2 2
3 3 3
enter the second matrix element=
1 1 1
2 2 2
3 3 3
multiply of the matrix=
6 6 6
12 12 12
18 18 18
                                                                             #aakash

Comments