fork download
  1. /*
  2. Name:Sheikh Md. Showrov Uddin Zishan
  3. Id: 230241003
  4. Report: Gauss Elimination
  5. */
  6.  
  7. #include <iostream>
  8. #include <iomanip>
  9. #include <vector>
  10. #include <cmath>
  11.  
  12. using namespace std;
  13.  
  14. void gaussElimination() {
  15. int n;
  16. cout << "Enter the order of square matrix: ";
  17. cin >> n;
  18.  
  19. vector<vector<double>> A(n, vector<double>(n + 1));
  20. vector<double> x(n);
  21.  
  22. cout << "Enter the elements of augmented matrix row-wise:\n";
  23. for (int i = 0; i < n; i++) {
  24. for (int j = 0; j <= n; j++) {
  25. cin >> A[i][j];
  26. }
  27. }
  28.  
  29.  
  30. for (int j = 0; j < n; j++) {
  31. // Partial Pivoting
  32. int maxRow = j;
  33. for (int i = j + 1; i < n; i++) {
  34. if (fabs(A[i][j]) > fabs(A[maxRow][j])) {
  35. maxRow = i;
  36. }
  37. }
  38. if (A[maxRow][j] == 0) {
  39. cout << "No unique solution exists (singular matrix)." << endl;
  40. return;
  41. }
  42. if (maxRow != j) {
  43. swap(A[j], A[maxRow]);
  44. }
  45.  
  46. // Eliminate
  47. for (int i = j + 1; i < n; i++) {
  48. double factor = A[i][j] / A[j][j];
  49. for (int k = j; k <= n; k++) {
  50. A[i][k] -= factor * A[j][k];
  51. }
  52. }
  53. }
  54.  
  55.  
  56. for (int i = n - 1; i >= 0; i--) {
  57. x[i] = A[i][n];
  58. for (int j = i + 1; j < n; j++) {
  59. x[i] -= A[i][j] * x[j];
  60. }
  61. if (A[i][i] == 0) {
  62. cout << "No unique solution exists (zero diagonal element)." << endl;
  63. return;
  64. }
  65. x[i] /= A[i][i];
  66. }
  67.  
  68.  
  69. cout << "\nThe solution is:\n";
  70. for (int i = 0; i < n; i++) {
  71. cout << "x" << i + 1 << " = " << fixed << setprecision(6) << x[i] << endl;
  72. }
  73. }
  74.  
  75. int main() {
  76. gaussElimination();
  77. return 0;
  78. }
Success #stdin #stdout 0.01s 5328KB
stdin
2 1 -1 8
-3 -1 2 -11
-2 1 2 -3
stdout
Enter the order of square matrix: Enter the elements of augmented matrix row-wise:

The solution is:
x1 = 1.500000
x2 = -6.500000