Display Elements Above Left Diagonal of Matrix

Write a program to allow the user to create a square matrix of order [m x m], where m > 3 and m < 10.

Display a suitable message for in invalid matrix size.

For correct size, allow the user to enter integers into this matrix.

Now display only those elements from that matrix that fall above the left diagonal.

import java.io.*;
class Diagonal{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Matrix size: ");
        int m = Integer.parseInt(br.readLine());
        if(m < 4 || m > 9){
            System.out.println("Size out of range!");
            return;
        }
        int a[][] = new int[m][m];
        System.out.println("Enter matrix elements:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                a[i][j] = Integer.parseInt(br.readLine());
            }
        }
        System.out.println("Original matrix:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
        System.out.println("Elements above right diagonal:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){ if(i == j || i > j)
                    System.out.print(" \t");
                else
                    System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.