C Program to print lower diagonal of a matrix

This C program will read a square matrix and print its lower diagonal.
Submitted by Abhishek Pathak, on April 09, 2017

Matrix is quite common mathematical tool used to solve various kinds of problems. Matrix has many properties and one of them is a lower diagonal of a matrix. Also see, program to read and print diagonal of a matrix.

The lower diagonal of a matrix is calculated quite easily. As the name says, only the lower diagonal elements are written as it is, while the upper elements are replaced by 0. Just like lower diagonal, there is also an upper diagonal matrix, which is just the opposite of former one.

Program to print lower triangle of a square matrix in C

#include <stdio.h>

#define ROW 3
#define COL 3

int main() {
	int matrix[ROW][COL] = {{2,3,4},{4,5,6},{6,7,8}};
	
	printf("Lower Triangular Matrix\n");

	for(int i=0; i<3; i++) {
		for(int j=0; j<3; j++) {
			if(i>=j)
				printf("%d ", matrix[i][j]);
			else
				printf("%d ", 0);
		}
		printf("\n");
	}

	return 0;
}

Output

Lower Triangular Matrix 
2 0 0 
4 5 0 
6 7 8 

In this program, we are taking a matrix of size 3x3 defined using #define ROW and COL. Here we are initializing the matrix in order to keep the program brief. Then we are accessing the matrix using 2 loops for rows and columns.

Inside the loop, we are checking if the row index is greater than equal to the column index. For our lower diagonal, the row index will always be greater than equal to the column index and thus the elements are written as it is. While the condition is not satisfied, the elements are replaced by 0.

C Two-dimensional Arrays Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.