C program to find upper triangular matrix

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

Example:
If elements of matrix are:
1 2 3
0 5 6
0 0 9

Output: Matrix is upper triangular

Required knowledge:

Basic C programming, For loop, Array, Matrix

Upper triangular matrix

Upper triangular matrix is a special type of square matrix whose all elements below the main diagonal is zero.
Upper triangular matrix

Algorithm to find upper triangular matrix:

To check whether a matrix is upper triangular or not we need to check whether all elements below main diagonal are zero.
For any matrix A if all elements Aij = 0 (Where i ≥ j)
If A[i][j] == 0 and i > j then it is upper triangular matrix.

Program:

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

#include <stdio.h>

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

    /*
     * 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 Upper triangular
     */
    isUpper = 1;
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            /*
             * If elements below the main diagonal (col<row)
             * is not equal to zero then it is not upper triangular matrix
             */
            if(col<row && A[row][col]!=0)
            {
                isUpper = 0;
            }
        }
    }
    
    /*
     * If it is upper triangular matrix
     */
    if(isUpper==1)
    {
        printf("This is a Upper triangular matrix.\n");

        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("This is Not a Upper triangular matrix.");
    }

    return 0;
} 
Output
X
_
Enter elements in matrix of size 3x3:
1 2 3
0 5 6
0 0 9
This is a Upper triangular matrix.
1 2 3
5 6
9

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment