Upper Triangular Matrix example in C++ programming language using for loop
In this article, you will learn how to explain the upper triangular matrix example in C++ programming language using for loop.
Examples
Enter the size of the matrix: 4
Enter the matrix's elements:
0 2 3 4
0 0 2 3
0 0 0 2
0 0 0 0
This is the Upper Triangular Matrix.
Enter the size of the matrix: 4
Enter the matrix's elements:
0 0 2 3
0 0 4 5
0 0 6 7
0 2 3 4
This not an Upper Triangular Matrix!
You should have knowledge of the following topics in the C++ programming language to understand this program:
- C++
main()
function - C++
for
loop statement - C++
if-else
statement - C++
cin
object - C++
cout
object
Source Code
// Upper Triangular Matrix example in C++ programming language using for loop
#include <bits/stdc++.h>
using namespace std;
int main() {
int size, flag = 0, i, j;
cout << "Enter the size of the matrix: ";
cin >> size;
int matrix[size][size];
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;
}
for (i = 1; i < size; i++) {
for (j = 0; j < i; j++) {
if (matrix[i][j] != 0)
flag = 0;
else
flag = 1;
}
}
if (flag == 1)
cout << "This is the Upper Triangular Matrix.\n";
else
cout << "This not an Upper Triangular Matrix!\n";
return 0;
}
Output
Enter the size of the matrix: 4
Enter the matrix's elements:
0 2 3 4
0 0 2 3
0 0 0 2
0 0 0 0
This is the Upper Triangular Matrix.
Explanation
In this program, we have taken input 4
size of the matrix then taken 16
elements 4 x 4 = 16
as inputs from the user to derivate this.
Then applied nested-for loop with the if-else condition to check the matrix's elements position is matching with Upper Triangular Matrix or not.