Write a program to multiply two matrices
Source Code:
#include <iostream>
#include <iomanip>
using namespace std;
void display(int mat[][2],int r){
for (int i=0;i<r;i++){
for(int j=0;j<2;j++){
cout<<setw(5)<<mat[i][j];}
cout<<endl;}
cout<<"---------------------------------------------------"<<endl;
}
void disp_product(int mat1[][2],int mat2[][2],int r){
int result[r][2];
cout<<"The product of the matrices is: "<<endl;
for (int i = 0; i < r; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = 0;
for (int k = 0; k < r; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];}
cout <<setw(5)<<result[i][j];
}
cout << endl;}}
int main(){
int r;
cout<<"Enter the number of rows: ";
cin>>r;
cout<<"---------------------------------------------------"<<endl;
int mat1[r][2],mat2[r][2];
for (int i=0;i<r;i++){
for(int j=0;j<2;j++){
cout<<"Enter the elements for the first matrix: ";
cin>>mat1[i][j];}}
cout<<"---------------------------------------------------"<<endl;
for (int i=0;i<2;i++){
for(int j=0;j<r;j++){
cout<<"Enter the elements for the second matrix: ";
cin>>mat2[i][j];}}
cout<<"---------------------------------------------------"<<endl;
cout<<"The first matrix is: "<<endl;
display(mat1,r);
cout<<"The second matrix is: "<<endl;
display(mat2,r);
disp_product(mat1,mat2,r);
return 0;}
0 Comments
Post a Comment