fork download
  1. /*
  2. Name: Anuska Alam
  3. Id: 230241021
  4. Report: Cramer's rule
  5. */
  6. #include <bits/stdc++.h>
  7. using namespace std;
  8.  
  9. // 2x2 determinant
  10. float det2x2(float m[2][2]) {
  11. return m[0][0]*m[1][1] - m[0][1]*m[1][0];
  12. }
  13.  
  14. // 3x3 determinant
  15. float det3x3(float m[3][3]) {
  16. return m[0][0]*(m[1][1]*m[2][2] - m[1][2]*m[2][1])
  17. - m[0][1]*(m[1][0]*m[2][2] - m[1][2]*m[2][0])
  18. + m[0][2]*(m[1][0]*m[2][1] - m[1][1]*m[2][0]);
  19. }
  20.  
  21. int main() {
  22. int n;
  23. cout << "Enter order of square matrix (2 or 3): ";
  24. cin >> n;
  25.  
  26. if (n != 2 && n != 3) {
  27. cout << "Only 2x2 or 3x3 matrices are supported.\n";
  28. return 0;
  29. }
  30.  
  31. float A[3][3] = {0}, B[3] = {0}; // initialized to 0
  32.  
  33. cout << "Enter coefficients of matrix A:\n";
  34. for (int i = 0; i < n; i++)
  35. for (int j = 0; j < n; j++)
  36. cin >> A[i][j];
  37.  
  38. cout << "Enter constants of vector B:\n";
  39. for (int i = 0; i < n; i++)
  40. cin >> B[i];
  41.  
  42. cout << fixed << setprecision(3);
  43.  
  44. if (n == 2) {
  45. float matA[2][2] = {
  46. {A[0][0], A[0][1]},
  47. {A[1][0], A[1][1]}
  48. };
  49.  
  50. float detA = det2x2(matA);
  51. cout << "\nDeterminant of A: " << detA << endl;
  52. if (detA == 0) {
  53. cout << "Matrix is singular; not uniquely solvable.\n";
  54. return 0;
  55. }
  56.  
  57. float A1[2][2] = {{B[0], A[0][1]}, {B[1], A[1][1]}};
  58. float A2[2][2] = {{A[0][0], B[0]}, {A[1][0], B[1]}};
  59.  
  60. float x1 = det2x2(A1) / detA;
  61. float x2 = det2x2(A2) / detA;
  62.  
  63. cout << "\nThe solution using Cramer's Rule:\n";
  64. cout << "x1 = " << x1 << endl;
  65. cout << "x2 = " << x2 << endl;
  66.  
  67. } else if (n == 3) {
  68. float detA = det3x3(A);
  69. cout << "\nDeterminant of A: " << detA << endl;
  70. if (detA == 0) {
  71. cout << "Matrix is singular; not uniquely solvable.\n";
  72. return 0;
  73. }
  74.  
  75. float A1[3][3], A2[3][3], A3[3][3];
  76. for (int i = 0; i < 3; i++) {
  77. A1[i][0] = B[i]; A1[i][1] = A[i][1]; A1[i][2] = A[i][2];
  78. A2[i][0] = A[i][0]; A2[i][1] = B[i]; A2[i][2] = A[i][2];
  79. A3[i][0] = A[i][0]; A3[i][1] = A[i][1]; A3[i][2] = B[i];
  80. }
  81.  
  82. float x1 = det3x3(A1) / detA;
  83. float x2 = det3x3(A2) / detA;
  84. float x3 = det3x3(A3) / detA;
  85.  
  86. cout << "\nThe solution using Cramer's Rule:\n";
  87. cout << "x1 = " << x1 << endl;
  88. cout << "x2 = " << x2 << endl;
  89. cout << "x3 = " << x3 << endl;
  90. }
  91.  
  92. return 0;
  93. }
Success #stdin #stdout 0s 5320KB
stdin
3
1 1 1
2 3 5
4 0 5

5 8 2
stdout
Enter order of square matrix (2 or 3): Enter coefficients of matrix A:
Enter constants of vector B:

Determinant of A: 13.000

The solution using Cramer's Rule:
x1 = 3.000
x2 = 4.000
x3 = -2.000