Note: For simplicity separate loops are used for each operation and printing answer, you can combine operation and print loops to save time. All the 4 operations i.e. Addition, subtraction, multiplication & division can be combined in one loop
Program to print addition, subtraction, multiplication and division of two N by N matrix
Take the size of arrays, the first array, and the second array from the user. For simplicity, each task will be done separately using nested loops. Each matrix element will be added with the other and stored in the addition matrix. similarly, subtraction, multiplication, and division of matrices will be done. Finally, print all four matrices. Checkout loops in C++
Code
#include<bits/stdc++.h>
using namespace std;
int main(){
cout<<"Enter size "<<endl;
int n;
cin>>n;
int a[n][n]; //1st array
int b[n][n]; //2nd array
int add[n][n]; //to store addition
int sub[n][n]; //to store subtraction
int mul[n][n]; //to store multiplication
int div[n][n]; //to store division
cout<<"Enter 1st Matrix "<<endl;
//Reading 1st matrix
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
cout<<"Enter 2nd Matrix "<<endl;
//Reading 2nd matrix
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>b[i][j];
}
}
//Addition
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
add[i][j]=a[i][j]+b[i][j];
}
}
//Subtraction
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
sub[i][j]=a[i][j]-b[i][j];
}
}
//Multiplication
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
mul[i][j]=a[i][j]*b[i][j];
}
}
//Division
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
div[i][j]=a[i][j]/b[i][j];
}
}
//Printing all the expected data
//Addition Matrix
cout<<"The Addition Matrix: "<<endl;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<add[i][j]<<" ";
}
cout<<endl;
}
//Subtraction Matrix
cout<<"The Subtraction Matrix: "<<endl;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<sub[i][j]<<" ";
}
cout<<endl;
}
//Multiplication Matrix
cout<<"The Multiplication Matrix: "<<endl;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<mul[i][j]<<" ";
}
cout<<endl;
}
//Division Matrix
cout<<"The Division Matrix: "<<endl;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<div[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
0 Comments