C++ Program to calculate Determinant of a Matrix


C++ Program to calculate Determinant of a Matrix

#include<iostream>
#include<math.h>
using namespace std;
int matrix_determinant( int matrx[10][10], int n) {   
   int determinant = 0;
   int sub_matrix[10][10];
   if (n == 2)
      return ((matrx[0][0] * matrx[1][1]) - (matrx[1][0] * matrx[0][1]));
   else {
      for (int k = 0; k < n; k++) {
            int subi = 0; 
            for (int i = 1; i < n; i++) {
               int subj = 0;
               for (int j = 0; j < n; j++) {
                  if (j == k)
                  continue;
                  sub_matrix[subi][subj] = matrx[i][j];
                  subj++;
               }
               subi++;
            }
            determinant = determinant + (pow(-1, k) * matrx[0][k] * matrix_determinant( sub_matrix, n - 1 ));
      }
   }
   return determinant;
}
int main() {
   int size, i, j;
   int matrx[10][10];   
   cout << "Enter the size of  matrix:\n";
   cin >> size;
   cout << "Enter the elements of  matrix:\n";
   for (i = 0; i < size; i++)
      for (j = 0; j < size; j++)
         cin >> matrx[i][j];
   cout<<"The entered matrix  is:"<<endl;
   for (i = 0; i < size; i++) {  
      for (j = 0; j < size; j++)
         cout << matrx[i][j] <<" ";
         cout<<endl;
   }
   cout<<"The Determinant of the matrix is :  "<< matrix_determinant(matrx, size);
   return 0;
}

 

Output:-

 


 

Leave a Reply

Your email address will not be published. Required fields are marked *