This is a C++ Program to Find if a Matrix is Invertible or Not.
The program takes a matrix and checks if it is invertible. An invertible matrix is a square matrix whose determinant exists.
1. The program takes a square matrix.
2. Using a function, determinant of the matrix is calculated.
3. If determinant is equal to 0, it is not an invertible matrix.
4. Else it is an invertible matrix.
5. The result is printed.
6. Exit.
Here is the source code of C++ Program to Find if a Matrix is Invertible or Not. The program output is shown below.
#include<iostream>
#include<math.h>
using namespace std;
double det(int n, double mat[10][10])
{
int subj = 0, subi = 0, i, j, c;
double submat[10][10], d = 0;
if (n == 2)
return ((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]));
else
{
for (c = 0; c < n; c++)
{
for (i = 1; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (j == c)
continue;
submat[subi][subj] = mat[i][j];
subj++;
}
subi++;
}
d = d + (pow(-1, c) * mat[0][c] * det(n - 1, submat));
}
}
return d;
}
int main(int argc, char **argv)
{
int n, i, j;
double mat[10][10];
cout << "Enter order of the matrix : ";
cin >> n;
cout << "Enter the elements of the matrix : ";
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
cin >> mat[j][i];
if (det(n, mat) != 0)
cout << "The given matrix is invertible.\n ";
else
cout << "The given matrix is not invertible.\n ";
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
cout << mat[i][j] << " ";
cout << "\n ";
}
}
1. The user is asked to enter the order of the matrix, i.e the size. It is stored in the variable ‘n’.
2. The elements of the matrix are asked to enter and stored in ‘mat’.
3. Using a function ‘det’, the determinant of the matrix is calculated.
4. In the main function, the value of determinant is returned. If it is equal to 0, the matrix is not invertible.
5. Else the entered matrix is invertible. The matrix is printed.
6. The result is then printed.
Case 1 : Enter order of the matrix : 2 Enter the elements of the matrix : 2 -3 -1 2 The given matrix is invertible. 2 -1 -3 2 Case 2 : Enter order of the matrix : 3 Enter the elements of the matrix : 1 2 3 4 5 6 7 8 9 The given matrix is not invertible. 1 4 7 2 5 8 3 6 9 Case 3 : Enter order of the matrix : 3 Enter the elements of the matrix : 1 0 0 0 1 0 0 0 1 The given matrix is invertible. 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.
- Check Programming Books
- Practice Programming MCQs
- Practice Computer Science MCQs
- Apply for C++ Internship
- Check C++ Books