In this article, you will learn how to Write a program to convert a square matrix into a lower triangular matrix in C++.
Examples:
1 2 3 4 5 6 7 8 9 | The size of the matrix is: 4 Enter the matrix's elements: 0 0 0 0 1 0 0 0 1 2 0 0 1 2 3 0 This is the Lower Triangular Matrix. |
1 2 3 4 5 6 7 8 9 | The size of the matrix is: 4 Enter the matrix's elements: 0 0 1 2 0 0 2 3 0 0 3 4 0 0 4 5 This not a Lower Triangular Matrix! |
You should have knowledge of the following topics in the C++ programming language to understand this program:
- C++
#define
directive - C++ Functions
- C++
main()
function - C++
for
loop statement - C++
if-else
statement - C++
cin
object - C++
cout
object
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // Lower Triangular Matrix example in C++ programming language using for loop #include <bits/stdc++.h> #define size 4 using namespace std; // @Utility function to check lower triangular matrix int CheckLowerTriangularMatrix(int matrix[size][size]) { int i, j; for (i = 0; i < size; i++) for (j = i + 1; j < size; j++) if (matrix[i][j] != 0) return 0; return 1; } // @Driver function to run the program int main() { int matrix[size][size], i, j; cout << "The Size of the matrix is: " << size << endl; cout << "\nEnter the matrix's elements:\n"; for(i = 0; i < size; i++) { for(j = 0; j < size; j++) cin >> matrix[i][j]; cout << endl; } if (CheckLowerTriangularMatrix(matrix)) cout << "This is the Lower Triangular Matrix.\n"; else cout << "This not a Lower Triangular Matrix!\n"; return 0; } |
Output:
1 2 3 4 5 6 7 8 9 | The Size of the matrix is: 4 Enter the matrix's elements: 0 0 0 0 1 0 0 0 1 2 0 0 1 2 3 0 This is the Lower Triangular Matrix. |
Explanation:
In this program, we have defined the size of the matrix is 4
using the C++ #define
directive.
Also, made a custom function named CheckLowerTriangularMatrix()
to check the given matrix is Lower Triangular Matrix or not.
Then taken 16
elements 4 x 4 = 16
as inputs from the user to derivate this.
Then we passed the matrix into CheckLowerTriangularMatrix() function and It checked for perhaps condition is matching or not.