This is a C++ Program to Find if an Array is an Identity Matrix.
The program takes a array and checks if it is an identity matrix. An identity matrix is a square matrix with main diagonal elements as 1 and rest 0.
1. The program takes the number of rows and columns of the matrix.
2. If they are not equal, it cannot be an identity matrix. The program is exited.
3. Else, the matrix is checked if only the main diagonal elements are 1 and rest are 0.
4. The result is printed.
5. Exit.
Here is the source code of C++ Program to Find if an Array is an Identity Matrix. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
int i, j, m, n, A[10][10], flag = 0;
cout << "Enter number of rows and columns : ";
cin >> m >> n;
if (m != n)
{
cout << "Matrix is not a square matrix!";
exit(0);
}
cout << "Enter array elements : ";
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
cin >> A[i][j];
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
{
if ((A[i][j] != 1) && (A[j][i] != 0))
{
flag = 1;
break;
}
}
if (flag == 0)
cout << "The given array is an identity matrix.\n ";
else
cout << "The given array is not an identity matrix.\n ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
cout << A[i][j] << " ";
cout << "\n ";
}
return 0;
}
1. The user is asked to enter the number of rows and columns.
2. If they are not equal, the array is not a square matrix, hence it cannot be an identity matrix. The program is exited.
3. Else, the elements are asked to enter and stored in ‘A’.
4. If the diagonal elements of the matrix are not 1 and non diagonal elements are not 0, the variable ‘flag’ is assigned value 1.
5. If flag is equal to 0, the entered array is an identity matrix, else it is not.
6. The result is then printed.
Case 1 : Enter number of rows and columns : 2 2 Enter array elements : 1 2 3 4 The given array is not an identity matrix. 1 2 3 4 Case 2 : Enter number of rows and columns : 3 2 Matrix is not a square matrix! Case 3 : Enter number of rows and columns : 3 3 Enter array elements : 1 0 0 0 1 0 0 0 1 The given array is an identity matrix. 1 0 0 0 1 0 0 0 1
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Apply for Computer Science Internship
- Check C++ Books
- Check Computer Science Books
- Apply for C++ Internship
- Check Programming Books