Java program to print boundary elements of the matrix

In this java program, we are going to read a matrix and printing its boundary elements. By IncludeHelp Last updated : December 23, 2023

Problem statement

Given a matrix and we have to print its boundary elements using java program.

Example

Input:
Row: 3
Cols: 4
Input matrix is:
1 2 5 6 
9 8 7 3
6 5 7 4

Output:
Matrix boundary elements
1	2	5	6	
9	 	 	3	
6	5	7	4

Program to print boundary elements of a matrix

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExArrayPrintBoundrayElements {
  public static void main(String args[]) throws IOException {
    // declare the objects.
    int i, j, m, n;

    // create the object of buffer class.
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    // enter rows and columns.
    System.out.print("Enter the rows : ");
    m = Integer.parseInt(br.readLine());
    System.out.print("Enter the columns : ");

    n = Integer.parseInt(br.readLine());

    //Creating the array
    int A[][] = new int[m][n];

    // Input the elements.
    for (i = 0; i < m; i++) {
      for (j = 0; j < n; j++) {
        // enter elements.
        System.out.println("Enter the elements : ");
        A[i][j] = Integer.parseInt(br.readLine());
      }
    }

    // this will print the boundary elements.
    System.out.println("The Boundary Elements are:");
    for (i = 0; i < m; i++) {
      for (j = 0; j < n; j++) {
        // condition for obtaining the boundary elements
        if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
          System.out.print(A[i][j] + "\t");
        else
          System.out.print(" \t");
      }
      System.out.println();
    }
  }
}

Output

Enter the rows : 3
Enter the columns : 4

Enter the elements : 1
Enter the elements : 2
Enter the elements : 5
Enter the elements : 6
Enter the elements : 9
Enter the elements : 8
Enter the elements : 7
Enter the elements : 3
Enter the elements : 6
Enter the elements : 5
Enter the elements : 7
Enter the elements : 4

The Boundary Elements are:
1	2	5	6	
9	 	 	3	
6	5	7	4	

Java Array Programs »

More Java Array Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.