In: Computer Science
Write a function named "check_matrix" which takes two matrices as parameters and returns 1 if the matrices are same or 0 otherwise. Set appropriate parameters and return type if necessary.
Please give a thumbs up if you find this answer helpful.
If it doesn't help, please comment before giving a thumbs down.
Since you have not mentioned the programming language, I have
provided the answer in C++.
If you want answer in different programming language, then let me
know in comment section.
Please look at my code and in case of indentation issues check the screenshots.
---------main.cpp---------------
#include <iostream>
using namespace std;
#define max 1000
//this function takes two matrices and their dimensions as
input
//returns 1 is matrices are same
//returns 0 if otherwise
int check_matrix(int matrix1[][max], int m1, int n1, int
matrix2[][max], int m2, int n2)
{
if(m1!= m2 || n1!=n2) //check if
dimensions of both matrices are different
return 0;
//return 0 if dimensions are
different
for(int i = 0; i < m1; i++){ //loop
through every row
for(int j = 0; j < n1;
j++){ //loop through every column
if(matrix1[i][j]
!= matrix2[i][j]) //if any element at same position
mismatches, then return 0
return 0;
}
}
return 1; //return 1 if all elements
matched
}
int main()
{
int m1, n1; //read dimensions of matrix
1
cout << "Enter number of rows in matrix 1:
";
cin >> m1;
cout << "Enter number of columns in matrix 1:
";
cin >> n1;
int matrix1[m1][max]; //declare matrix
1
for(int i = 0; i < m1; i++){
cout << "Enter row " <<
i+1 << " of matrix 1: ";
for(int j = 0; j < n1;
j++){
cin >>
matrix1[i][j]; //read matrix 1
}
}
cout << "\nThe matrix 1 is: \n";
for(int i = 0; i < m1; i++){
for(int j = 0; j < n1;
j++){
cout<<
matrix1[i][j] << " "; //print matrix 1
}
cout << endl;
}
int m2, n2; //read dimensions of matrix
1
cout << "\n\nEnter number of rows in matrix 2:
";
cin >> m2;
cout << "Enter number of columns in matrix 2:
";
cin >> n2;
int matrix2[m2][max]; //declare matrix
2
for(int i = 0; i < m2; i++){
cout << "Enter row " <<
i+1 << " of matrix 2: ";
for(int j = 0; j < n2;
j++){
cin >>
matrix2[i][j]; //read matrix 2
}
}
cout << "\nThe matrix 2 is: \n";
for(int i = 0; i < m2; i++){
for(int j = 0; j < n2;
j++){
cout<<
matrix2[i][j] << " "; //print matrix 2
}
cout << endl;
}
int val = check_matrix(matrix1, m1, n1, matrix2,
m2, n2); //check if matrices are same
if(val == 1)
//if return value is 1, they are same
cout << "\nmatrix 1 and
matrix 2 are same" << endl;
else
//if
return value is 0, they are different
cout << "\nmatrix 1 and
matrix 2 are different" << endl;
return 0;
}
----------Screenshots--------------
----------Output--------------
------------------------------------------------
Please Do comment if you need any clarification.
Please let me know if you are facing any issues.
Please Rate the answer if it helped.
Thankyou