C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Display Matrix Upper and Lower Triangle

C Program: Display Matrix Upper and Lower Triangle

C

#include <stdio.h>

 

int main() {

    int a[10][10];

    int i, j, n;

 

    // Input order of square matrix

    printf("Enter the order of the square matrix (n x n): ");

    scanf("%d", &n);

 

    // Input elements of matrix

    printf("\nEnter elements of the matrix:\n");

    for (i = 0; i < n; i++) {

        for (j = 0; j < n; j++) {

            scanf("%d", &a[i][j]);

        }

    }

 

    // Display original matrix

    printf("\nOriginal Matrix:\n");

    for (i = 0; i < n; i++) {

        for (j = 0; j < n; j++) {

            printf("%d\t", a[i][j]);

        }

        printf("\n");

    }

 

    // Display upper triangular matrix

    printf("\nUpper Triangular Matrix:\n");

    for (i = 0; i < n; i++) {

        for (j = 0; j < n; j++) {

            if (i <= j)

                printf("%d\t", a[i][j]);

            else

                printf("0\t");

        }

        printf("\n");

    }

 

    // Display lower triangular matrix

    printf("\nLower Triangular Matrix:\n");

    for (i = 0; i < n; i++) {

        for (j = 0; j < n; j++) {

            if (i >= j)

                printf("%d\t", a[i][j]);

            else

                printf("0\t");

        }

        printf("\n");

    }

 

    return 0;

}

Output

 
INPUT :
Enter the order of the square matrix (n x n): 3
Enter elements of the matrix:
1 2 3
4 5 6
7 8 9

OUTPUT :
Original Matrix:
1   2   3
4   5   6
7   8   9

Upper Triangular Matrix:
1   2   3
0   5   6
0   0   9

Lower Triangular Matrix:
1   0   0
4   5   0
7   8   9


Explanation

  1. A square matrix (n × n) is entered by the user.
  2. The upper triangle includes elements where i ≤ j.
  3. The lower triangle includes elements where i ≥ j.
  4. Other positions are replaced with zeros for clarity.
  5. The program prints the original, upper, and lower matrices.