Example HTML page

C Program for printing the lower triangle elements in a matrix

In this section, we are writing a program for printing the lower triangle ( lower diagonal ) elements of a given matrix with order mXn. (m==n) i.e. it should be a square matrix.

For example, if the order of matrix is 3X3.

Then, to do this, we require one input matrix.

For example:

First matrix:

1 2 3

3 4 6

7 8 9

result is : 2 3 6

To write this program, do the following things.

Step 1: read the order of the first matrix

Step 2: read the first matrix

Step 3: write the condition for checking the lower triangle elements and print the result.

Observe the following diagram

assume the given matrix is

1  2 3

4 5 6

7 8 9

if we use the condition

i==j ; we get diagonal elements

i>j ; we get lower diagonal elements

i<j ; we get upper diagonal elements.

 

#include <stdio.h>
 
int main()
{
   int  first[10][10], result[10][10],m, n, i,j;
   // read the order of the first matrix.
   printf("Enter the number of rows and columns of matrix\n");
   scanf("%d%d", &m, &n);
   
   // reading the first matrix 
   printf("Enter the elements of first matrix\n");
   for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
         scanf("%d", &first[i][j]);
         
  
 // if 'i > j' print the lower diagonal element.
     
   for (i = 0; i < m; i++)
   {
   	for (j = 0; j < n; j++)
        {
        	if(i>j)
        	{
        		printf("%d \t",first[i][j]);
			}
		}
   }
       

   return 0;
}
Program for displaying lower diagonal elements

Output:

Command Prompt

Enter the number of rows and columns of matrix
3
3
Enter the elements of first matrix
1 2 3
4 5 6
7 8 9

4 7 8

i<j ; we get upper diagonal elements.

use this condition in the above program to get upper diagonal elements.

#include <stdio.h>
 
int main()
{
   int  first[10][10], result[10][10],m, n, i,j;
   // read the order of the first matrix.
   printf("Enter the number of rows and columns of matrix\n");
   scanf("%d%d", &m, &n);
   
   // reading the first matrix 
   printf("Enter the elements of first matrix\n");
   for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
         scanf("%d", &first[i][j]);
         
  
 // if 'i < j' print the upper diagonal element.
     
   for (i = 0; i < m; i++)
   {
   	for (j = 0; j < n; j++)
        {
        	if(i<j)
        	{
        		printf("%d \t",first[i][j]);
			}
		}
   }
       

   return 0;
}
Program for displaying upper diagonal elements

Output:

Command Prompt

Enter the number of rows and columns of matrix
3
3
Enter the elements of first matrix
1 2 3
4 5 6
7 8 9

2 3 6

 

Thank you for visiting our blog.

Example HTML page

Leave a Reply

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

Pin It on Pinterest