C program to find lower triangular matrix

Write a C program to read elements in a matrix and check whether the matrix is a lower triangular matrix or not. C program to find whether the matrix is lower triangular or not.

Example: If elements of the matrix are:
1 0 0
4 5 0
7 8 9

Output: Matrix is lower triangular

Required knowledge:

Basic C programming, For loop, Array, Matrix

Lower triangular matrix

Lower triangular matrix is a special square matrix whose all elements above the main diagonal is zero.
Lower triangular matrix

Algorithm to find lower triangular matrix:

To find whether a matrix is lower triangular or not we need to check if all elements above the main diagonal of the matrix is zero.

For any matrix A if elements Aij = 0 (Where j ≥ i)
If arr[i][j] == 0 and j > i then it is a lower triangular matrix.

Program:

/**
 * C program to find lower triangular matrix
 */

#include <stdio.h>

int main()
{
    int A[3][3];
    int row, col, isLower;

    /*
     * Reads elements in matrix from user
     */
    printf("Enter elements in matrix of size 3x3: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /*
     * Checks whether the matrix is lower triangular matrix
     */
    isLower = 1;
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            /*
             * If elements above main diagonal(col>row)
             * is not equal to zero(A[row][col]!=0)
             */
            if(col>row && A[row][col]!=0)
            {
                isLower = 0;
            }
        }
    }

    /*
     * If the matrix is lower triangular matrix
     */
    if(isLower == 1)
    {
        printf("Matrix is Lower triangular matrix: \n");

        /*
         * Prints elements of lower triangular matrix
         */
        for(row=0; row<3; row++)
        {
            for(col=0; col<3; col++)
            {
                if(A[row][col]!=0)
                {
                    printf("%d ", A[row][col]);
                }
            }

            printf("\n");
        }
    }
    else
    {
        printf("Matrix is not a Lower triangular matrix");
    }

    return 0;
} 
Output
X
_
Enter elements in matrix of size 3x3:
1 0 0
4 5 0
7 8 9
Matrix is Lower triangular matrix:
1
4 5
7 8 9

Happy coding ;)


You may also like

Labels: , , ,