Write a program in c++ to input and print the multiplication of two matrix

Write a program in c++ to input and print the multiplication of two matrix




#include <iostream>
using namespace std;
int main(){
    int r1,r2,c1,c2;
    cout<<"Enter Rows of First Matrix : ";
    cin>>r1;
    cout<<"Enter Columns of First Matrix : ";
    cin>>c1;
    cout<<"Enter Rows of Second Matrix : ";
    cin>>r2;
    cout<<"Enter Columns of Second Matrix : ";
    cin>>c2;
    int a[r1][c1],b[r2][c2],c[r1][c2];
    if (c1==r2)
    { //taking elements of first matrix
        cout<<"Enter Elements Of first Matrix "<<endl;
       for (int i = 0; i < r1; i++)
        {
                for (int j = 0; j < c1; j++)
                {
                    cin>>a[i][j];               
                }
        }
        //printing first matrix 
        cout<<"Elements Of first Matrix are "<<endl;
        for (int i = 0; i < r1; i++)
         {
                for (int j = 0; j < c1; j++)
                 {
                    cout<<a[i][j]<<" ";               
                 }
               cout<<endl;
        }
        //taking elements of second matrix
        cout<<"Enter Elements Of second Matrix "<<endl;
       for (int i = 0; i < r2; i++)
        {
                for (int j = 0; j < c2; j++)
                {
                    cin>>b[i][j];               
                }
        }
        //printing second matrix
        cout<<"Elements Of second Matrix are "<<endl;
        for (int i = 0; i < r2; i++)
         {
                for (int j = 0; j < c2; j++)
                 {
                    cout<<b[i][j]<<" ";               
                 }
               cout<<endl;
        }
        //multiplying first and second matrix
        for (int i = 0; i < r1; i++) 
        {
                for (int j = 0; j < c2; j++) 
                {
                    c[i][j] = 0;
                    for (int k = 0; k < r2; k++) 
                    {
                        c[i][j] = c[i][j] + a[i][k] * b[k][j];
                    }
                }
        }
        //printing multiplied matrix
            cout<<"Matrix after multiplication "<<endl;
             for (int i = 0; i < r1; i++)
              {
                for (int j = 0; j < c2; j++)
                 {
                    cout<<" " << c[i][j] << " ";
                }
                cout<<endl;
             }

        
    } else 
        {
            cout<<"Sorry!! can't Multiply";
        }
    
}





Share:

0 Comments:

Post a Comment

Pageviews