Program opened below. You can scroll through the algorithm, Java code and output.
Program 55
Display the Upper Triangular Part of a Matrix
Question
Accept a square matrix and display its upper triangular part, replacing lower triangular elements with zero.
Algorithm
Step 1: Start the program and accept the order n of the square matrix.
Step 2: Declare a two-dimensional integer array of order n.
Step 3: Read the matrix elements using nested loops.
Step 4: Display a heading for the upper triangular matrix.
Step 5: Visit each row i and column j of the matrix.
Step 6: Compare the column index j with the row index i.
Step 7: If j is greater than or equal to i, display the original matrix element.
Step 8: Otherwise display zero at that position.
Step 9: Continue until every element in the row has been processed.
Step 10: Move to the next row and repeat the same condition.
Step 11: Print each matrix row on a separate line.
Step 12: Stop the program.
Java program
Javaimport java.util.*;
class UpperTriangle
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter order: ");
int n = sc.nextInt();
if (n < 1 || n > 10)
{
System.out.println("Invalid order");
return;
}
int[][] a = new int[n][n];
System.out.println("Enter matrix elements:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = sc.nextInt();
}
}
System.out.println("Upper triangular matrix:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i <= j)
{
System.out.print(a[i][j] + "\t");
}
else
{
System.out.print("0\t");
}
}
System.out.println();
}
}
}Sample output
Input: Input matrix: 1 2 3 / 4 5 6 / 7 8 9
Output: 1 2 3
0 5 6
0 0 9