Display Matrix Boundary Elements in Java

Write a program in Java with the following specifications:
Class name: PatternMatrix
Data members/instance variables:
int r: to store the number of rows.
int c: to store the number of columns.
int s: to store the sum of the elements.
int a[][]: to store the matrix elements.
Methods:
PatternMatrix(): constructor to initialize the variables.
void input(): to input the number of rows and columns, and also the matrix elements.
void display(): to display the boundary elements and diagonal elements in matrix form, along with the sum of the elements.

Also write the main() method to create an object of the class and call the methods accordingly.

import java.io.*;
class PatternMatrix{
    private int r;
    private int c;
    private int s;
    private int a[][];
    public PatternMatrix(){
        r = 0;
        c = 0;
        s = 0;
    }
    public void input()throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Number of rows: ");
        r = Integer.parseInt(br.readLine());
        System.out.print("Number of columns: ");
        c = Integer.parseInt(br.readLine());
        System.out.println("Enter matrix elements:");
        a = new int[r][c];
        for(int i = 0; i < r; i++){
            for(int j = 0; j < c; j++){
                a[i][j] = Integer.parseInt(br.readLine());
                s += a[i][j];
            }
        }
    }
    public void display(){
        System.out.println("\nBoundary elements:");
        for(int i = 0; i < r; i++){
            for(int j = 0; j < c; j++){
                if(i == 0 || i == r - 1 || j == 0 || j == c - 1)
                    System.out.print(a[i][j] + "\t");
                else
                    System.out.print("\t");
            }
            System.out.println();
        }
        if(r == c){
            System.out.println("\nDiagonal elements:");
            for(int i = 0; i < r; i++){
                for(int j = 0; j < c; j++){
                    if(i == j || i + j == r - 1)
                        System.out.print(a[i][j] + "\t");
                    else
                        System.out.print("\t");
                }
                System.out.println();
            }
        }
        System.out.println("\nSum of the elements: " + s);
    }
    public static void main(String args[])throws IOException{
        PatternMatrix obj = new PatternMatrix();
        obj.input();
        obj.display();
    }
}

Leave a Reply