Answer:
#include<iostream>
using namespace std;
int** makeMatrix(int n)
{
int** newM = new int*[n];
for(int i = 0; i < n; i++)
{
newM[i] = new int[n];
for(int j = 0;j < n; j++)
{
cin >> newM[i][j];
}
}
return newM;
}
void printMatrix(int** A, int n)
{
for(int i = 0; i < n; i++)
{
for(int j = 0;j < n; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
}
bool sumEqual(int** A,int** B, int n)
{
int sum1 = 0, sum2 = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
sum1 += A[i][j];
sum2 += B[i][j];
}
}
return sum1 == sum2;
}
bool isEqual(int** A, int** B, int n)
{
for(int i = 0; i <n; i++)
{
for(int j = 0; j < n; j++)
{
if(A[i][j] != B[i][j])
{
return false;
}
}
}
return true;
}
int diagonal(int** A, int n)
{
int product = 1;
for(int i = 0; i < n; i++)
{
product *= A[i][i];
}
return product;
}
int** sumMatrix(int** A, int** B, int n)
{
int** C = new int*[n];
for(int i = 0; i < n; i++)
{
C[i] = new int[n];
for(int j = 0; j < n; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
int** product(int** A, int**B, int n)
{
int** C = new int*[n];
for(int i = 0; i < n; i++)
{
C[i] = new int[n];
for(int j = 0; j < n; j++)
{
C[i][j] = 0;
for(int k = 0; k < n; k++)
{
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
int** subtractMatrix(int** A, int** B, int n)
{
int** C = new int*[n];
for(int i = 0; i < n; i++)
{
C[i] = new int[n];
for(int j = 0; j < n; j++)
{
C[i][j] = A[i][j] - B[i][j];
}
}
return C;
}
int main()
{
cout << "Enter the size of the matrices : ";
int n;
cin >> n;
int** m1 = makeMatrix(n);
int** m2 = makeMatrix(n);
cout << endl << "Print the first matrix : "<< endl;
printMatrix(m1,n);
cout << "Print the second matrix : " << endl;
printMatrix(m2,n);
cout << "Is sum equal : " << sumEqual(m1,m2,n) << endl;
cout << "Are these two matrices equal : " << isEqual(m1,m2,n) << endl;
cout << "Product of diagonal elements of first matrix is : " << diagonal(m1,n) << endl;
cout << "Sum of two matrices is : " << endl;
int** sum = sumMatrix(m1,m2,n);
printMatrix(sum,n);
cout << "Product of two matrices is : " << endl;
int** pro = product(m1,m2,n);
printMatrix(pro,n);
cout << "Difference of two matrices is: " << endl;
int** difference = subtractMatrix(m1,m2,n);
printMatrix(difference, n);
return 0;
}
Step-by-step explanation:
All the required functions have been implemented. See the output snippet which is added for better understanding.