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