fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <iomanip>
  4. using namespace std;
  5.  
  6. int main() {
  7. int n;
  8. cout << "Enter the order of square matrix: ";
  9. cin >> n;
  10.  
  11. vector<vector<double>> A(n, vector<double>(n));
  12. vector<vector<double>> L(n, vector<double>(n, 0));
  13. vector<vector<double>> U(n, vector<double>(n, 0));
  14. vector<double> B(n), Y(n), X(n);
  15.  
  16. cout << "Enter matrix elements:\n";
  17. for (int i = 0; i < n; i++)
  18. for (int j = 0; j < n; j++)
  19. cin >> A[i][j];
  20.  
  21. cout << "Enter the constant terms:\n";
  22. for (int i = 0; i < n; i++)
  23. cin >> B[i];
  24.  
  25. // LU Decomposition
  26. for (int j = 0; j < n; j++) {
  27. for (int i = 0; i < n; i++) {
  28. if (i <= j) {
  29. U[i][j] = A[i][j];
  30. for (int k = 0; k < i; k++)
  31. U[i][j] -= L[i][k] * U[k][j];
  32. if (i == j)
  33. L[i][j] = 1;
  34. } else {
  35. L[i][j] = A[i][j];
  36. for (int k = 0; k < j; k++)
  37. L[i][j] -= L[i][k] * U[k][j];
  38. L[i][j] /= U[j][j];
  39. }
  40. }
  41. }
  42.  
  43. // Forward substitution to solve L*Y = B
  44. for (int i = 0; i < n; i++) {
  45. Y[i] = B[i];
  46. for (int j = 0; j < i; j++)
  47. Y[i] -= L[i][j] * Y[j];
  48. }
  49.  
  50. // Backward substitution to solve U*X = Y
  51. for (int i = n - 1; i >= 0; i--) {
  52. X[i] = Y[i];
  53. for (int j = i + 1; j < n; j++)
  54. X[i] -= U[i][j] * X[j];
  55. X[i] /= U[i][i];
  56. }
  57.  
  58. // Output L
  59. cout << "\n[L]:\n";
  60. for (int i = 0; i < n; i++) {
  61. for (int j = 0; j < n; j++)
  62. cout << fixed << setprecision(3) << setw(8) << L[i][j];
  63. cout << endl;
  64. }
  65.  
  66. // Output U
  67. cout << "\n[U]:\n";
  68. for (int i = 0; i < n; i++) {
  69. for (int j = 0; j < n; j++)
  70. cout << fixed << setprecision(3) << setw(8) << U[i][j];
  71. cout << endl;
  72. }
  73.  
  74. // Output Y
  75. cout << "\n[Y]: ";
  76. for (int i = 0; i < n; i++)
  77. cout << fixed << setprecision(3) << Y[i] << " ";
  78. cout << endl;
  79.  
  80. // Output X
  81. cout << "\n[X]: ";
  82. for (int i = 0; i < n; i++)
  83. cout << fixed << setprecision(3) << X[i] << " ";
  84. cout << endl;
  85.  
  86. return 0;
  87. }
  88.  
Success #stdin #stdout 0s 5256KB
stdin
2 4 -2
4 9 -3
-2 -3 -7
stdout
Enter the order of square matrix: Enter matrix elements:
Enter the constant terms:

[L]:
   1.000   0.000
   1.000   1.000

[U]:
   4.000  -2.000
   0.000  11.000

[Y]: -3.000 1.000 

[X]: -0.705 0.091