C Online Compiler
Example: Display Upper Triangular Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Display Upper Triangular Matrix #include <stdio.h> int main() { int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int rows = 3; int cols = 3; printf("Original Matrix:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } printf("\nUpper Triangular Matrix:\n"); for (int i = 0; i < rows; i++) { // Iterate through rows for (int j = 0; j < cols; j++) { // Iterate through columns // Step 1: Check if the current element is on or above the main diagonal // The main diagonal is where i == j. Elements above have i < j. if (i <= j) { printf("%d ", matrix[i][j]); // Step 2: Print the element } else { printf("0 "); // Step 3: Print 0 for elements below the main diagonal } } printf("\n"); // Move to the next line after each row } return 0; }
Output
Clear
ADVERTISEMENTS