In: Computer Science
Write a recursive program in C++ to compute the determinant of an NxN matrix, A. Your program should ask the user to enter the value of N, followed by the path of a file where the entries of the matrix could be found. It should then read the file, compute the determinant and return its value. Compile and run your program.
#include<iostream>
#include<math.h>
using namespace std;
//find the determinant
int deter( int mat[10][10], int size) {
int det = 0,k,a,b; //set the determinant to 0
int m1[30][30],m1i,m1j;//declare the mtrix
if (size == 2)//compute the determinant for size 2
return ((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]));
//return the determinant
//compute determinant for the matrix
else {
for (k = 0; k < size; k++) {
m1i = 0; //set the row index of m1 to 0
for (a = 1; a < size; a++) {
m1j = 0; //set the column index of m1 to 0
for (b = 0; b < size; b++) {
if (b == k)
continue;
m1[m1i][m1j] = mat[a][b]; //assign mat[a][b] to m1
m1j++;
}
m1i++;
}//recursively call to deter() to compute the determinant
det = det + (pow(-1, k) * mat[0][k] * deter( m1, size - 1 ));
}
}
return det; //return the determinant of the matrix
}
//driver program
int main()
{
int size, i, j;
int mat[30][30];
//enter the size of matrix
cout << "Enter the size of the matrix:\n";
cin >> size;
//input the matrix elements
cout << "Enter the elements of the matrix:\n";
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
cin >> mat[i][j];
//display the given matrix
cout<<"The entered matrix is:"<<endl;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++)
cout << mat[i][j] <<" ";
cout<<endl;
}
//print the determinant
cout<<"Determinant of the matrix is "<< deter(mat,
size);
return 0;
}
OUTPUT