Let’s take the input of 3x3 matrix, means total 9 elements, in 2D array using keyboard at runtime.
With the help of it and for loops, we can display only lower triangle in 3X3 matrix.
The logic to print lower triangle elements is as follows −
for(i=0;i<3;i++){ for(j=0;j<3;j++){ if(i>=j) //lower triangle index b/s 1st index>=2nd index printf("%d",array[i][j]); else printf(" "); //display blank in non lower triangle places } printf("\n"); }
Program
Following is the C program to display only the lower triangle elements in a 3x3 2D array −
#include<stdio.h> int main(){ int array[3][3],i,j; printf("enter 9 numbers:"); for(i=0;i<3;i++){ for(j=0;j<3;j++) scanf("%d",&array[i][j]); } for(i=0;i<3;i++){ for(j=0;j<3;j++){ if(i>=j) //lower triangle index b/s 1st index>=2nd index printf("%d",array[i][j]); else printf(" "); //display blank in non lower triangle places } printf("\n"); } return 0; }
Output
The output is given below −
enter 9 numbers: 1 2 3 1 3 4 4 5 6 1 13 456
Consider another program which can print the upper triangle for a given 3X3 matrix form.
Example
#include<stdio.h> int main(){ int array[3][3],i,j; printf("enter 9 numbers:"); for(i=0;i<3;i++){ for(j=0;j<3;j++) scanf("%d",&array[i][j]); } for(i=0;i<3;i++){ for(j=0;j<3;j++){ if(i<=j) //upper triangle printf("%d",array[i][j]); else printf(" "); //display blank in lower triangle places } printf("\n"); } return 0; }
Output
The output is as follows −
enter 9 numbers: 2 3 4 8 9 6 1 2 3 2 3 4 9 6 3