Display Elements Above Right Diagonal of Matrix

Write a program to create a square matrix of size [m × m] of type integer.

The value of ‘m’ is entered by the user and ensure that m > 3 and m < 10.

For an invalid size, display a suitable error message.

Now allow the user to enter integers into this matrix.

Once the array is full with integers, display the elements that fall above the right diagonal.

Example:
INPUT:
M = 4
Original Matrix:

1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 7

OUTPUT:
Elements above right diagonal:

1 2 3
5 6
9
import java.io.*;
class RightDiagonal{
    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 < m - 1)
                    System.out.print(a[i][j] + "\t");
                else
                    System.out.print("\t");
            }
            System.out.println();
        }
    }
}

2 thoughts on “Display Elements Above Right Diagonal of Matrix”

  1. Sir,a program is given which states that:
    Write a program to declare a square matrix M [ ] [ ] of order ‘N’ where ‘N’ must be greater than 3 and less than 10. Allow the user to accept three different characters from the keyboard and fill the array according to the instruction given below: (i) Fill the four corners of the square matrix by character 1. (ii) Fill the boundary elements of the matrix (except the four corners) by character 2. (iii) Fill the non-boundary elements of the matrix by character 3. Test your program with the following data and some random data:
    INPUT: N = 4
    FIRST CHARACTER: @
    SECOND CHARACTER: ?
    THIRD CHARACTER: #
    OUTPUT: @ ? ? @
    ? # # ?
    ? # # ?
    @ ? ? @
    Use Scanner class

Leave a Reply

%d bloggers like this: