Lower Triangular Matrix example in C++ programming language using for loop
In this article, you will learn how to explain the Lower Triangular Matrix example in C++ programming language using for loop.
Examples
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.
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
// 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
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.