# C++ Program to Compute Determinant of a Matrix

«
»
This is a C++ Program to compute the determinant of the given matrix.

Here is source code of the C++ Program to Compute Determinant of a Matrix. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `#include<conio.h>`
2. `#include<iostream>`
3. `#include<math.h>`
4. ` `
5. `using namespace std;`
6. `double d = 0;`
7. `double det(int n, double mat);`
8. `double det(int n, double mat)`
9. `{`
10. `    double submat;`
11. `    if (n == 2)`
12. `        return ((mat * mat) - (mat * mat));`
13. `    else`
14. `    {`
15. `        for (int c = 0; c < n; c++)`
16. `        {`
17. `            int subi = 0; //submatrix's i value`
18. `            for (int i = 1; i < n; i++)`
19. `            {`
20. `                int subj = 0;`
21. `                for (int j = 0; j < n; j++)`
22. `                {`
23. `                    if (j == c)`
24. `                        continue;`
25. `                    submat[subi][subj] = mat[i][j];`
26. `                    subj++;`
27. `                }`
28. `                subi++;`
29. ` `
30. `            }`
31. `            d = d + (pow(-1, c) * mat[c] * det(n - 1, submat));`
32. `        }`
33. `    }`
34. `    return d;`
35. `}`
36. `int main(int argc, char **argv)`
37. `{`
38. ` `
39. `    cout << "Enter the dimension of the matrix:\n";`
40. `    int n;`
41. `    cin >> n;`
42. `    double mat;`
43. `    cout << "Enter the elements of the matrix:\n";`
44. `    for (int i = 0; i < n; i++)`
45. `    {`
46. `        for (int j = 0; j < n; j++)`
47. `        {`
48. `            cin >> mat[j][i];`
49. `        }`
50. `    }`
51. `    cout << "The determinant of the given matrix is: " << det(n, mat);`
52. `	return 0;`
53. `}`

Output:

```\$ g++ DeterminantOfMatrix.cpp
\$ a.out

Enter the dimension of the matrix:
3
Enter the elements of the matrix:
3 5 2
8 4 8
2 4 7
The determinant of the given matrix is: -164

Enter the dimension of the matrix:
4
Enter the elements of the matrix:
9 5 2 5
9 5 3 7
6 5 4 8
1 5 3 7
The determinant of the given matrix is: 0```

Sanfoundry Global Education & Learning Series – 1000 C++ Programs. 