Prerequisite - Multidimensional Arrays in C / C++
Given a two dimensional array, Write a program to print lower triangular matrix and upper triangular matrix.
- Lower triangular matrix is a matrix which contains elements below principal diagonal including principal diagonal elements and rest of the elements are 0.
- Upper triangular matrix is a matrix which contains elements above principal diagonal including principal diagonal elements and rest of the elements are 0.
LOWER TRIANGULAR :
UPPER TRIANGULAR :
Examples :
Input : matrix[3][3] = {1 2 3
4 5 6
7 8 9}
Output :
Lower : 1 0 0 Upper : 1 2 3
4 5 0 0 5 6
7 8 9 0 0 9
Input : matrix[3][3] = {7 8 9
3 2 1
6 5 4}
Output :
Lower : 7 0 0 Upper : 7 8 9
3 2 0 0 2 1
6 5 4 0 0 4
Steps:
- For lower triangular matrix, we check the index position i and j i.e. row and column respectively. If column position is greater than row position we simply make that position 0.
- For upper triangular matrix, we check the index position i and j i.e. row and column respectively. If column position is smaller than row position we simply make that position 0.
OutputLower triangular matrix:
1 0 0
4 5 0
7 8 9
Upper triangular matrix:
1 2 3
0 5 6
0 0 9
Time Complexity: O(row x col)
Auxiliary Space: O(1), since no extra space has been taken.