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 1 2 3
0 0 1 2
0 0 0 1
0 0 0 0
This is the Upper Triangular Matrix.
Enter the size of the matrix: 4
Enter the matrix's elements:
0 1 2 3
0 0 1 2
1 2 3 4
1 2 3 5
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
printf()
function
Source Code
// Upper Triangular Matrix example in C programming language using for loop
#include <stdio.h>
int main() {
int size, flag = 0, i, j;
printf("Enter the size of the matrix: ");
scanf("%d", &size);
int matrix[size][size];
printf("\nEnter the matrix's elements:\n");
for(i = 0; i < size; i++) {
for(j = 0; j < size; j++)
scanf("%d", &matrix[i][j]);
printf("\n");
}
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)
printf("This is the Upper Triangular Matrix.\n");
else
printf("This not an Upper Triangular Matrix!\n");
return 0;
}
Output
Enter the size of the matrix: 4
Enter the matrix's elements:
0 1 2 3
0 0 1 2
0 0 0 1
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.