7. Program to display the upper triangular matrix
💡Code:
import java.util.Scanner;
public class UpperTriangularMatrix7078 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the order of the square matrix from the user
System.out.print("Enter the order of the square matrix: ");
int order = scanner.nextInt();
// Create the square matrix
int[][] matrix = new int[order][order];
System.out.println("Enter elements for the matrix:");
inputMatrix(matrix, scanner);
// Display the upper triangular matrix
System.out.println("Upper Triangular Matrix:");
displayUpperTriangularMatrix7078(matrix);
// Close the scanner
scanner.close();
}
// Function to input elements into a square matrix
private static void inputMatrix(int[][] matrix, Scanner scanner) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print("Enter element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
matrix[i][j] = scanner.nextInt();
}
}
}
// Function to display the upper triangular matrix
private static void displayUpperTriangularMatrix7078(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (i <= j) {
System.out.print(matrix[i][j] + " ");
} else {
System.out.print("0 ");
}
}
System.out.println(); // Move to the next row
}
}
}
📸Output :