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[10][11], x[10];
  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. // Forward Elimination (Upper Triangular Form)
  20. for(int k=0; k<n-1; k++) {
  21. for(int i=k+1; i<n; i++) {
  22. double ratio = A[i][k]/A[k][k];
  23. for(int j=k; j<=n; j++) {
  24. A[i][j] -= ratio * A[k][j];
  25. }
  26. }
  27. }
  28.  
  29. // Backward 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] = x[i]/A[i][i];
  36. }
  37.  
  38. // Print Solution
  39. cout << "\nThe solution is:\n";
  40. cout << fixed << setprecision(6);
  41. for(int i=0; i<n; i++) {
  42. cout << "x" << i+1 << " = " << x[i] << endl;
  43. }
  44.  
  45. return 0;
  46. }
  47.  
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