C Program to Display Upper Triangular Matrix

This C program calculates and displays the upper triangular matrix of a given square matrix. An upper triangular matrix is a special matrix where all the elements below the main diagonal are zero. This program prompts the user to enter the elements of a square matrix and then prints the upper triangular matrix.

Problem statement

Write a C program to input a 3×3 matrix from the user and display its upper triangular form. The upper triangular matrix contains the elements of the original matrix above the main diagonal (including the main diagonal), while the elements below the main diagonal are replaced with zeros. Implement a function displayUpperTriangular() that takes a 2D array representing the matrix as an argument and displays the upper triangular matrix.

The program first prompts the user to enter the elements of the matrix. It then calls the displayUpperTriangular() function to compute and display the upper triangular matrix based on the input.

C Program to Display Upper Triangular Matrix

#include <stdio.h>

#define SIZE 3

void displayUpperTriangular(int matrix[SIZE][SIZE]) {
    printf("Upper Triangular Matrix:\n");
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            if (j >= i)
                printf("%d ", matrix[i][j]);
            else
                printf("0 ");
        }
        printf("\n");
    }
}

int main() {
    int matrix[SIZE][SIZE];
    
    printf("=== Upper Triangular Matrix Calculator ===\n");
    printf("Please enter the elements of a %dx%d matrix:\n", SIZE, SIZE);
    
    // Input matrix elements
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Display the upper triangular matrix
    displayUpperTriangular(matrix);
    
    return 0;
}

How it works

  1. The program prompts the user to enter the elements of a square matrix. The SIZE constant represents the size of the matrix (in this case, 3×3).
  2. The user enters the matrix elements one by one.
  3. The displayUpperTriangular() function takes the input matrix as an argument and prints the upper triangular matrix. It uses nested loops to iterate over the matrix elements and checks whether the current element is above or on the main diagonal. If it is, the element is printed; otherwise, a zero is printed.
  4. After displaying the upper triangular matrix, the program terminates.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program finds the Greatest Common Divisor (GCD) of two given numbers. Problem Statement Write a C program that...
This C program calculates the roots of a quadratic equation of the form ax^2 + bx + c = 0....
This C program allows you to find the length of a linked list, which is the number of nodes present...