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]; // augmented matrix [A|B]
  11.  
  12. // Input augmented matrix
  13. cout << "Enter the elements of augmented matrix row-wise:\n";
  14. for(int i=0; i<n; i++) {
  15. for(int j=0; j<=n; j++) {
  16. cin >> A[i][j];
  17. }
  18. }
  19.  
  20. // Gauss-Jordan elimination
  21. for(int i=0; i<n; i++) {
  22. // Make the diagonal element 1
  23. double diag = A[i][i];
  24. for(int j=0; j<=n; j++) {
  25. A[i][j] = A[i][j] / diag;
  26. }
  27.  
  28. // Make other elements in current column 0
  29. for(int k=0; k<n; k++) {
  30. if(k != i) {
  31. double factor = A[k][i];
  32. for(int j=0; j<=n; j++) {
  33. A[k][j] = A[k][j] - factor * A[i][j];
  34. }
  35. }
  36. }
  37. }
  38.  
  39. // Display Final Row-Echelon Form
  40. cout << fixed << setprecision(4);
  41. cout << "\nFinal Row-Echelon Form [A|B]:\n";
  42. for(int i=0; i<n; i++) {
  43. for(int j=0; j<=n; j++) {
  44. cout << A[i][j] << " ";
  45. }
  46. cout << endl;
  47. }
  48.  
  49. // Display solution
  50. cout << "\nThe solution is:\n";
  51. for(int i=0; i<n; i++) {
  52. cout << "x" << i+1 << " = " << A[i][n] << endl;
  53. }
  54.  
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0.01s 5320KB
stdin
3
1 1 1 5
2 3 5 8
4 0 5 2
stdout
Enter the order of square matrix: Enter the elements of augmented matrix row-wise:

Final Row-Echelon Form [A|B]:
1.0000 0.0000 0.0000 3.0000 
0.0000 1.0000 0.0000 4.0000 
0.0000 0.0000 1.0000 -2.0000 

The solution is:
x1 = 3.0000
x2 = 4.0000
x3 = -2.0000