Home

A program to print the upper triangle and lower triangle of a matrix

C Programming Language 059

The following code shows how to write a program to print the upper triangle and lower triangle of a matrix.

Program

#include <stdio.h>

void main()
{
    int a[10][10], m, n, i, j, tr = 0;
    printf("Enter order m,m [m x m]: ");
    scanf("%d", &m);

    printf("Enter values:\n");
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < m; j++)
        {
            scanf("%d", &a[i][j]);
        }
    }

    printf("Upper triangle:\n");
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < m; j++)
        {
            if (i <= j)
            {
                printf("%d\t", a[i][j]);
            }
        }
        printf("\n");
    }

    printf("Lower triangle:\n");
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < m; j++)
        {
            if (i >= j)
            {
                printf("%d\t", a[i][j]);
            }
        }
        printf("\n");
    }

    printf("\n");
}

Result

Enter order m,m [m x m]: 3
Enter values:
1 2 3
4 5 6
7 8 9
Upper triangle:
1       2       3
5       6
9
Lower triangle:
1
4       5
7       8       9


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments