I've wrote a C++ program to calculate the determinant of a matrix:
#include <iostream>
#include <string>
double getDeterminant(double arr[], int dimension);
int main() {
//First, the user has to enter the dimension of the matrix
int dimension;
std::cout << "Please enter dimension of Matrix: ";
std::cin >> dimension;
std::cout << std::endl;
double matrix[dimension][dimension];
//Now, the user has to enter the matrix line by line, seperated by commas
std::string str;
for(int i = 1; i <= dimension; i++) {
std::cout << "Enter line " << i << " only seperated by commas: ";
std::cin >> str;
std::cout << std::endl;
str = str + ',';
std::string number;
int count = 0;
for(int k = 0; k < str.length(); k++) {
if(str[k] != ',') {
number = number + str[k];
}
else {
matrix[i - 1][count] = std::stod(number);
number = "";
count++;
}
}
}
//Conversion to a onedimensional matrix to be able to give it over as a parameter
double array[dimension * dimension];
int k = 0;
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++) {
array[k] = matrix[i][j];
k++;
}
}
//Output
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << "Determinant of the matrix is : " << getDeterminant(array, dimension) << std::endl;
return 0;
}
double getDeterminant(double array[], int dimension) {
//Formula for 2x2-matrix
if(dimension == 2) {
return array[0] * array[3] - array[1] * array[2];
}
//Conversion back to 2D-array
double matrix[dimension][dimension];
int k = 0;
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++) {
matrix[i][j] = array[k];
k++;
}
}
double result = 0;
int sign = 1;
for(int i = 0; i < dimension; i++) {
//Submatrix
double subMatrix[dimension - 1][dimension -1];
for(int m = 1; m < dimension; m++) {
int z = 0;
for(int n = 0; n < dimension; n++) {
if(n != i) {
subMatrix[m-1][z] = matrix[m][n];
z++;
}
}
}
//Conversion of the submatrix to 1D-array
double array2[(dimension - 1) * (dimension - 1)];
int k = 0;
for(int x = 0; x < dimension - 1; x++) {
for(int y = 0; y < dimension - 1; y++) {
array2[k] = subMatrix[x][y];
k++;
}
}
//recursive call
result = result + sign * matrix[0][i] * getDeterminant(array2, dimension -1);
sign = -sign;
}
return result;
}
I would appreciate any suggestions on improving the code!
You can find the follow-up question here.