Friday, July 23, 2021

Multiplication of two square Matrices

To multiply an m×n matrix by an n×q matrix, the n's must be the same, and the result is an m×q matrix.
m×n n×q = m×q
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Write a program in C for multiplication of two square Matrices.
#include<stdio.h>
int main()
{
    int a[10][10],b[10][10],result[10][10];
    int i,j,r1,c1,r2,c2;
    int sum,k;

    
    printf("Enter number of Rows of matrix a: ");
    scanf("%d",&r1);
    printf("Enter number of Cols of matrix a: ");
    scanf("%d",&c1);

    printf("Enter number of Rows of matrix b: ");
    scanf("%d",&r2);
    printf("Enter number of Cols of matrix b: ");
    scanf("%d",&c2);   

    /*Testing the multiplication rule of two matrix*/   

    if(c1==r2) //col1 and row2 comparision
    {   //if conditon begin

/*---------------------------------------------------*/
    printf("\n Enter elements of matrix a: \n");
   
    for(i=0;i< r1;i++) //row times repeation
    {
        for(j=0;j< c1;j++) //col times repeation        
      {
               scanf("%d",&a[i][j]);
        }
    }
/*---------------------------------------------------*/

    printf("\nEnter elements of matrix b: \n");
   
    for(i=0;i< r2;i++) //row times repeation
    {
        for(j=0;j< c2;j++) //col times repeation  
      {
            scanf("%d",&b[i][j]);
        }
    }
/*---------------------------------------------------*/
              /*Multiplication of two matrices*/
        for(i=0;i<r1;i++)
        {
            for(j=0;j< c2;j++)
            {
                sum=0;
                for(k=0;k<c1;k++)
                {
                    sum=sum + (a[i][k]*b[k][j]);
                }
                result[i][j]=sum;
            }
        }
/*---------------------------------------------------*/
       /* Multiplication output*/
       for(i=0;i< r1;i++)
       {
          for(j=0;j< c2;j++)
          {
            printf("result of multiplication is [%d,%d] : ",i,j);
            printf("%d\n",result[i][j]);
          }
       }   

    
   }   //if condition close
/*---------------------------------------------------*/

    else
    {
        printf("\nMultiplication can not be done.");
    }
   
 
    return 0;
}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OUTPUT
Enter number of Rows of matrix a: 2
Enter number of Cols of matrix a: 2
Enter number of Rows of matrix b: 2
Enter number of Cols of matrix b: 2

Enter elements of matrix a:
1
2
3
4

Enter elements of matrix b:
1
2
3
4
result of multiplication is [0,0] : 7
result of multiplication is [0,1] : 10
result of multiplication is [1,0] : 15
result of multiplication is [1,1] : 22

No comments:

Post a Comment