The program takes a matrix as input from the user and converts it into an upper triangular matrix using Gaussian elimination.
#include
#include
using namespace std;
void convertToUpperTriangular(vector>& matrix) {
int n = matrix.size();
for (int i = 0; i < n - 1; i++) {
for (int k = i + 1; k < n; k++) {
double factor = matrix[k][i] / matrix[i][i];
for (int j = i; j < n; j++) {
matrix[k][j] -= factor * matrix[i][j];
}
}
}
}
int main() {
int n;
cout << "Enter the size of the matrix: ";
cin >> n;
vector> matrix(n, vector(n));
cout << "Enter the matrix elements row by row:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
convertToUpperTriangular(matrix);
cout << "Upper Triangular Matrix:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
Enter the size of the matrix: 2
Enter the matrix elements row by row:
1
2
3
4
Upper Triangular Matrix:
1 2
0 -2