fork download
  1. #include<iostream>
  2. #include<iomanip>
  3. using namespace std;
  4.  
  5. int main() {
  6. int n;
  7. cout << "Enter the order of square matrix: ";
  8. cin >> n;
  9.  
  10. double A[20][20], x[20];
  11.  
  12. cout << "Enter the elements of augmented matrix row-wise:\n";
  13. for(int i = 0; i < n; i++) {
  14. for(int j = 0; j <= n; j++) {
  15. cin >> A[i][j];
  16. }
  17. }
  18.  
  19. // Gaussian Elimination (Forward Elimination)
  20. for(int j = 0; j < n; j++) {
  21. for(int i = j+1; i < n; i++) {
  22. double ratio = A[i][j] / A[j][j];
  23. for(int k = 0; k <= n; k++) {
  24. A[i][k] -= ratio * A[j][k];
  25. }
  26. }
  27. }
  28.  
  29. // Back Substitution
  30. for(int i = n-1; i >= 0; i--) {
  31. x[i] = A[i][n];
  32. for(int j = i+1; j < n; j++) {
  33. x[i] -= A[i][j] * x[j];
  34. }
  35. x[i] /= A[i][i];
  36. }
  37.  
  38. // Output the solution
  39. cout << fixed << setprecision(6);
  40. cout << "The solution is:\n";
  41. for(int i = 0; i < n; i++) {
  42. cout << "x" << i+1 << " = " << x[i] << endl;
  43. }
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0.01s 5288KB
stdin
3
3
6
-9
15
2
4
-6
10
-2
-3
4
-6
stdout
Enter the order of square matrix: Enter the elements of augmented matrix row-wise:
The solution is:
x1 = -nan
x2 = -nan
x3 = -nan