/*
Name: Anuska Alam
Id: 230241021
Report: Cramer's rule
*/
#include <bits/stdc++.h>
using namespace std;
// 2x2 determinant
float det2x2(float m[2][2]) {
return m[0][0]*m[1][1] - m[0][1]*m[1][0];
}
// 3x3 determinant
float det3x3(float m[3][3]) {
return m[0][0]*(m[1][1]*m[2][2] - m[1][2]*m[2][1])
- m[0][1]*(m[1][0]*m[2][2] - m[1][2]*m[2][0])
+ m[0][2]*(m[1][0]*m[2][1] - m[1][1]*m[2][0]);
}
int main() {
int n;
cout << "Enter order of square matrix (2 or 3): ";
cin >> n;
if (n != 2 && n != 3) {
cout << "Only 2x2 or 3x3 matrices are supported.\n";
return 0;
}
float A[3][3] = {0}, B[3] = {0}; // initialized to 0
cout << "Enter coefficients of matrix A:\n";
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> A[i][j];
cout << "Enter constants of vector B:\n";
for (int i = 0; i < n; i++)
cin >> B[i];
cout << fixed << setprecision(3);
if (n == 2) {
float matA[2][2] = {
{A[0][0], A[0][1]},
{A[1][0], A[1][1]}
};
float detA = det2x2(matA);
cout << "\nDeterminant of A: " << detA << endl;
if (detA == 0) {
cout << "Matrix is singular; not uniquely solvable.\n";
return 0;
}
float A1[2][2] = {{B[0], A[0][1]}, {B[1], A[1][1]}};
float A2[2][2] = {{A[0][0], B[0]}, {A[1][0], B[1]}};
float x1 = det2x2(A1) / detA;
float x2 = det2x2(A2) / detA;
cout << "\nThe solution using Cramer's Rule:\n";
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
} else if (n == 3) {
float detA = det3x3(A);
cout << "\nDeterminant of A: " << detA << endl;
if (detA == 0) {
cout << "Matrix is singular; not uniquely solvable.\n";
return 0;
}
float A1[3][3], A2[3][3], A3[3][3];
for (int i = 0; i < 3; i++) {
A1[i][0] = B[i]; A1[i][1] = A[i][1]; A1[i][2] = A[i][2];
A2[i][0] = A[i][0]; A2[i][1] = B[i]; A2[i][2] = A[i][2];
A3[i][0] = A[i][0]; A3[i][1] = A[i][1]; A3[i][2] = B[i];
}
float x1 = det3x3(A1) / detA;
float x2 = det3x3(A2) / detA;
float x3 = det3x3(A3) / detA;
cout << "\nThe solution using Cramer's Rule:\n";
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
cout << "x3 = " << x3 << endl;
}
return 0;
}