Upper triangular matrix in C | Lower triangular matrix in C

Written by

studymite

C program to check whether a matrix is upper triangular and lower triangular without using an array

Here, We’ll learn to write a program to check whether the given matrix is upper triangular or not in C programming language.

Upper Triangular Matrix: An upper triangular matrix is a special type of matrix that has all of its elements below the main diagonal (the diagonal from the top left to the bottom right of the matrix) set to zero.

Source: https://commons.wikimedia.org/wiki/File:Triangular_matrix.svg
  1. Initialize variables is_uppr and is_lowr to 1.
  2. Take input for the number of rows and the matrix.
  3. Iterate through the matrix.
  4. If any element below the main diagonal is non-zero, set is_uppr to 0.
  5. If any element above the main diagonal is non-zero, set is_lowr to 0.
  6. If is_uppr or is_lowr is 1, print "Upper Triangular".
  7. Else, print "Not Upper Triangular".

Code:

#include <stdio.h>

int main()
{
    int n, i, j, is_uppr = 1, is_lowr = 1, a;

    printf("Enter the number of rows:: ");
    scanf("%d", &n);

    printf("Enter the Array::\n");
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            scanf("%d", &a);
            if (j > i && a != 0) //Check for upper triangular condition
                is_uppr = 0;
            if (j < i && a != 0) //Check for lower triangular condition
                is_lowr = 0;
        }
    }
    if (is_uppr == 1 || is_lowr == 1)
        printf("Upper Triangular\n");
    else
        printf("Not Upper Triangular\n");

    return 0;
}

Output

Enter the number of rows:: 4
Enter the Array::
1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4
Upper Triangular

Enter the number of rows:: 3
Enter the Array::
1 2 0
3 4 5
6 7 8
Not Upper Triangular

Upper triangular matrix in C | Lower triangular matrix in C