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][10], L[10][10], U[10][10], B[10], Y[10], X[10];
  11.  
  12. // Input Matrix A
  13. cout << "Enter matrix element:\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. // Input Vector B
  21. cout << "Enter the constant terms: ";
  22. for(int i=0; i<n; i++) {
  23. cin >> B[i];
  24. }
  25.  
  26. // Initialize L and U
  27. for(int i=0; i<n; i++) {
  28. for(int j=0; j<n; j++) {
  29. if(i==j)
  30. L[i][j] = 1.0;
  31. else
  32. L[i][j] = 0.0;
  33. U[i][j] = 0.0;
  34. }
  35. }
  36.  
  37. // LU Decomposition
  38. for(int j=0; j<n; j++) {
  39. for(int i=0; i<=j; i++) {
  40. double sum = 0.0;
  41. for(int k=0; k<i; k++)
  42. sum += L[i][k]*U[k][j];
  43. U[i][j] = A[i][j] - sum;
  44. }
  45. for(int i=j+1; i<n; i++) {
  46. double sum = 0.0;
  47. for(int k=0; k<j; k++)
  48. sum += L[i][k]*U[k][j];
  49. L[i][j] = (A[i][j] - sum) / U[j][j];
  50. }
  51. }
  52.  
  53. // Display L
  54. cout << fixed << setprecision(3);
  55. cout << "\n[L]:\n";
  56. for(int i=0; i<n; i++) {
  57. for(int j=0; j<n; j++)
  58. cout << L[i][j] << " ";
  59. cout << endl;
  60. }
  61.  
  62. // Display U
  63. cout << "\n[U]:\n";
  64. for(int i=0; i<n; i++) {
  65. for(int j=0; j<n; j++)
  66. cout << U[i][j] << " ";
  67. cout << endl;
  68. }
  69.  
  70. // Forward Substitution to solve L.Y = B
  71. for(int i=0; i<n; i++) {
  72. double sum = 0.0;
  73. for(int j=0; j<i; j++)
  74. sum += L[i][j] * Y[j];
  75. Y[i] = (B[i] - sum) / L[i][i];
  76. }
  77.  
  78. // Display Y
  79. cout << "\n[Y]: ";
  80. for(int i=0; i<n; i++)
  81. cout << Y[i] << " ";
  82. cout << endl;
  83.  
  84. // Backward Substitution to solve U.X = Y
  85. for(int i=n-1; i>=0; i--) {
  86. double sum = 0.0;
  87. for(int j=i+1; j<n; j++)
  88. sum += U[i][j] * X[j];
  89. X[i] = (Y[i] - sum) / U[i][i];
  90. }
  91.  
  92. // Display X
  93. cout << "\n[X]: ";
  94. for(int i=0; i<n; i++)
  95. cout << X[i] << " ";
  96. cout << endl;
  97.  
  98. return 0;
  99. }
  100.  
Success #stdin #stdout 0.01s 5316KB
stdin
3
2 4 -2
4 9 -3
-2 -3 -7
stdout
Enter the order of square matrix: Enter matrix element:
Enter the constant terms: 
[L]:
1.000 0.000 0.000 
2.000 1.000 0.000 
-1.000 1.000 1.000 

[U]:
2.000 4.000 -2.000 
0.000 1.000 1.000 
0.000 0.000 -10.000 

[Y]: 0.000 0.000 -0.000 

[X]: -0.000 0.000 0.000