Write a program in c++ to check if entered 3x3 matrix is a diagonal matrix
#include <iostream>
using namespace std;
int main()
{
int a[3][3], flag = 0;
//Loop to enter elements of matrix
cout << "Enter Elements of Array : ";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cin >> a[i][j];
}
}
// Loop to print matrix
cout<<"Entered Matrix : ";
for (int i = 0; i < 3; i++)
{
cout << endl;
for (int j = 0; j < 3; j++)
{
cout << a[i][j] << " ";
}
}
//Loop to check for diagonal matix
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (i == j && a[i][j] == 0)
{
flag = 1;
break;
}
else if (i != j && a[i][j] != 0)
{
flag = 1;
break;
}
}
}
if (flag == 1)
{
cout << "\n This is not a Diagonal Matrix ";
}
else
cout << "\n This is Diagonal Matrix ";
return 0;
}
OUTPUT
Enter Elements of Array : 12
34
23
56
45
11
67
76
54
Entered Matrix :
12 34 23
56 45 11
67 76 54
This is not a Diagonal Matrix