# Java program to display upper triangular matrix

Hi coders! many of you solve array problems. As we know an array is used to implement matrix elements so I am here to show you how to display upper triangular matrix in Java programming language. This seems a bit tricky but easy to solve, you just need to know matrix properly.

Suppose there is a matrix:

`{{``1``, 6``, ``3``},  `
`{``4``, ``5``, 7``},  `
`{9``, 2``, 8``}};`
Here if you want to display upper triangular matrix for this matrix then it will display like :
```1 6 3
0 5 7
0 0 8```

So here we have printed the upper triangular matrix also we have replaced all other elements with zero.
This is totally up to you that what you want at the places of other elements if you want space you can alter the code accordingly.
Steps to display the upper triangular matrix :

1. Declare the number of rows and columns for the matrix array.
2. Assign matrix elements.
3. In the function which displays the upper triangular matrix use two for loops in which one is for the row and the other for the column.
4.  Now we check the index position i and j i.e row and column respectively. If column position is smaller than row position we will make that position 0 else print the element.

Java code for the same is provided below:

```// Java program to display  Upper triangular
// matrix of an array
import java.util.*;
class UpperTriangularMatrix {

// function that displays upper triangular matrix
private static void upperTriangularMatrixDisplay(int matrixArr[][], int row, int col) {
int i, j;
for (i = 0; i < row; i++){
for (j = 0; j < col; j++){
if (i > j) {
System.out.print("0" + " ");
}
else
System.out.print(matrixArr[i][j] + " ");
}
System.out.println();
}
}

// main function
public static void main(String args[]) {
//declaring row and column as integer variable and assigning them the value as 3
int row = 3, col = 3;
//declaring 2D Array of integers matrixArr
int matrixArr[][] = {{1, 6, 3},
{4, 5, 7},
{9, 2, 8}};

System.out.println("Upper triangular matrix is: ");
//Here we have called the function upperTriangiularMatrixDisplay with
//passing the arguments matrix array, number of rows and the number of columns.
upperTriangularMatrixDisplay(matrixArr, row, col);
}
}```
```Output :
Upper  triangular matrix is :

1 6 3
0 5 7
0 0 8```

Here in the above code since we are using nested loops concepts and there are two loops so the time complexity for the above code is O(n^2).

Hope you like the solution.