C++ Program To Calculate Determinant Of A Matrix
#include<iostream>
#include<math.h>
using
namespace std;
double
d = 0;
double
det(int n, double mat[10][10]);
double
det(int n, double mat[10][10]){
double
submat[10][10];
if
(n == 2) // set the matrix (must be square) to find determinant.
return
((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]));
else
{
for
(int c = 0; c < n; c++) {
int
subi = 0;
for
(int i = 1; i < n; i++) {
int
subj = 0;
for
(int 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
n;
double
mat[10][10];
cout
<< "Dimension Of The Matrix: ";
cin
>> n;
cout
<< "\nEnter The Matrix Elements: \n";
for
(int i = 0; i < n; i++) {
for
(int j = 0; j < n; j++) {
cin
>> mat[j][i];
}}
cout
<< "\nThe Determinant Of The Above Matrix = " << det(n,
mat);
return
0;
}
C++ Program To Find The Adjoint And Inverse Of A Matrix
#include<bits/stdc++.h>
using
namespace std;
#define
N 3
void
getCofactor(int A[N][N], int temp[N][N], int p, int q, int n) {
int
i = 0, j = 0;
for
(int row = 0; row < n; row++) {
for
(int col = 0; col < n; col++) {
if
(row != p && col != q) {
temp[i][j++]
= A[row][col];
if
(j == n - 1) {
j
= 0;
i++;
}}}}}
int
determinant(int A[N][N], int n) {
int
D = 0;
if
(n == 1)
return
A[0][0];
int
temp[N][N];
int
sign = 1;
for
(int f = 0; f < n; f++) {
getCofactor(A,
temp, 0, f, n);
D
+= sign * A[0][f] * determinant(temp, n - 1);
sign
= -sign;
}
return
D;
}
void
adjoint(int A[N][N],int adj[N][N]) {
if
(N == 1) {
adj[0][0]
= 1;
return;
}
int
sign = 1, temp[N][N];
for
(int i=0; i<N; i++) {
for
(int j=0; j<N; j++) {
getCofactor(A,
temp, i, j, N);
sign
= ((i+j)%2==0)? 1: -1;
adj[j][i]
= (sign)*(determinant(temp, N-1));
}}}
bool
inverse(int A[N][N], float inverse[N][N]) {
int
det = determinant(A, N);
if
(det == 0) {
cout
<< " Singular Matrix, Can't Find Its Inverse.\n";
return
false;
}
int
adj[N][N];
adjoint(A,
adj);
for
(int i=0; i<N; i++)
for
(int j=0; j<N; j++)
inverse[i][j]
= adj[i][j]/float(det);
return
true;
}
template<class
T>
void
display(T A[N][N]) {
for
(int i=0; i<N; i++) {
for
(int j=0; j<N; j++)
cout
<< A[i][j] << " ";
cout
<< endl;
}}
int
main() {
int
A[N][N],i,j;
cout<<"*** Adjoint & Inverse Of A 3x3 Matrix *** \n";
cout<<"\nEnter
9 Numbers: \n";
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
cin
>> A[i][j];
}}
int
adj[N][N];
float
inv[N][N];
cout
<< "\nInput Matrix:\n";
display(A);
cout
<< "\nAdjoint Of The Matrix:\n";
adjoint(A,
adj);
display(adj);
cout
<< "\nInverse Of The Matrix:";
if
(inverse(A, inv)) { cout << "\n";
display(inv);
}
return
0;
}