C++ Program to Find the Determinant of a Given Matrix

«
»
This C++ program displays the value of the determinant of a particular matrix. A determinant is a value associated with a square matrix. It can be computed from the entries of the matrix by a specific arithmetic expression, while other ways to determine its value exist as well.

Here is the source code of the C++ program to display the determinant of matrices upto order 10. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is given below.

  1. /*
  2.  * C++ Program to Find the Determinant of a Given Matrix
  3.  */
  4. #include<iostream>
  5. #include<math.h>
  6. #include<conio.h>
  7. using namespace std;
  8. double d = 0;
  9. double det(int n, double mat[10][10])
  10. {
  11.     int c, subi, i, j, subj;
  12.     double submat[10][10];  
  13.     if (n == 2) 
  14.     {
  15.         return( (mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]));
  16.     }
  17.     else
  18.     {  
  19.         for(c = 0; c < n; c++)
  20.         {  
  21.             subi = 0;  
  22.             for(i = 1; i < n; i++)
  23.             {  
  24.                 subj = 0;
  25.                 for(j = 0; j < n; j++)
  26.                 {    
  27.                     if (j == c)
  28.                     {
  29.                         continue;
  30.                     }
  31.                     submat[subi][subj] = mat[i][j];
  32.                     subj++;
  33.                 }
  34.                 subi++;
  35.             }
  36.         d = d + (pow(-1 ,c) * mat[0][c] * det(n - 1 ,submat));
  37.         }
  38.     }
  39.     return d;
  40. }
  41. int main()
  42. {
  43.     int n;
  44.     cout<<"enter the order of matrix" ;
  45.     cin>>n;
  46.     double mat[10][10];
  47.     int i, j;
  48.     cout<<"enter the elements"<<endl;
  49.     for(i=0;i<n;i++)
  50.     {
  51.         for(j=0;j<n;j++)
  52.         {
  53.             cin>>mat[i][j];
  54.         }
  55.     }
  56.     cout<<"\ndeterminant"<<det(n,mat);
  57.     getch();
  58. }

advertisement
Output
enter the order of matrix 3
enter the elements
3
6
2
8
6
5
9
1
6
 
determinant    -17

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn