Write a program for multiplication of two matrices

// Write a program for multiplication of two matrices

#include
int main(){
     int row_size1,col_size1,row_size2,col_size2,i=0,j=0,k=0;
     printf("Enter Matrix1 row size:");
     scanf("%d",&row_size1);                 // matrix row size input from user
     printf("Enter Matrix1 column size:");  
     scanf("%d",&col_size1);                 // matrix column size input from user
     int matrix1[row_size1][col_size1];
    
     // user input for matrix1 elements
     printf("Enter Matrix1 Elements");
     for(i=0;i<row_size1;i++){
             for(j=0;j<col_size1;j++){
                     scanf("%d",&matrix1[i][j]);
             }
     }
    
     printf("Enter Matrix2 row size:");
     scanf("%d",&row_size2);                 // matrix row size input from user
     printf("Enter Matrix2 column size:");  
     scanf("%d",&col_size2);
     int matrix2[row_size2][col_size2];       // defining matrix arrays
          
     // user input for matrix2 elements
     printf("Enter Matrix2 Elements");
     for(i=0;i<row_size2;i++){
             for(j=0;j<col_size2;j++){
                     scanf("%d",&matrix2[i][j]);
             }
     }
 
//check if multiplication of matrices is possible
     if(col_size1!=row_size2){
            printf("Multiplication of matrices is not possible if Column size of first matrix doesn't equals row size of second matrix");
            exit(0);                  
     }
 
     // if multiplication is possible, calculate it and print it
int output[row_size1][col_size2];
     for(i=0;i<row_size1;i++){
            for(j=0;j<col_size2;j++){
                     output[i][j]=0;
            }
     }
 
// multiplication of two matrices
     for(i=0;i<row_size1;i++){
            for(j=0;j<col_size1;j++){
                     for(k=0;k<col_size2;k++){
                           output[i][k] = output[i][k]+matrix1[i][j]*matrix2[j][k];
                     }
            }
     }
    
     // printing output matrix
     printf("Multiplication Matrix:\n");
     for(i=0;i<row_size1;i++){
            for(j=0;j<col_size2;j++){
                     printf("%d ",output[i][j]);
            }
            printf("\n");
     }
     getchar();
     getchar();
}

No comments:

Post a Comment