Create a script with user defined function that will find the determinant of any
ID: 3681477 • Letter: C
Question
Create a script with user defined function that will find the determinant of any square matrix as long as the size of the matrix is less than or equal to 4. (i.e. determinant of n X n matrix with n 4).
Here are the conditions:
The User should be prompted each time when a numerical input is needed.
The calculation of matrix determinant has to be done in the user defined function.
You need to write DETAILED comment on this script.
Please use DEV C++, preferably with functions like printf() scanf() etc. THANKS IN ADVANCE.
Explanation / Answer
#include<iostream>
#include<math.h>
using namespace std;
double d = 0;
double determinant(int n, double mat[10][10]) //actual
{
int c, subi, i, j, subj;
double submat[10][10];
if (n == 2)
return( (mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1])); //if matrix size is 2, directlt calculate bc-ad
else
{
for(c = 0; c < n; c++) //iterate over the matrix
{
subi = 0; //
for(i = 1; i < n; i++) // finds submatrix of main matrix which always holds 2X2 matrix of main matrix
{
subj = 0;
for(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)); // calls recursively after filling up the submatrix
}
}
return d;
}
int main()
{
int n;
cout<<"enter the order of matrix" ; // input order of matrix
cin>>n;
if(n>4 && n<1)
{
cout<<"Only square matrix of order atmost 4 is acceptable";
return 0; //return if order is greater than 4
}
double mat[10][10];
int i, j;
cout<<"enter the matrix elements"<<endl; //input matrix elements
for(i=0;i<n;i++)
for(j=0;j<n;j++)
cin>>mat[i][j]; //read elements
cout<<" Determinant of provided matrix is"<<determinant(n,mat); /// call determinant function
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.