Thursday, September 4, 2025
HomeLanguagesJavaJava Program to Print Boundary Elements of the Matrix

Java Program to Print Boundary Elements of the Matrix

Given a matrix of size Row x Col Print the boundary elements of the matrix. Boundary elements are those elements which are not surrounded by elements on all four directions, i.e. elements in the first row, first column, last row and last column.

Example:

Input :
         1 2 3
         4 5 6
         7 8 9
Output:  
        1 2 3
        4   6
        7 8 9

Approach:

  1. Take the matrix as input from the user of N × M dimension.
  2. Print the border elements of the matrix using for loop.

Below is the implementation of the problem statement:

Java




// Java Program to Print Boundary
// Elements of the Matrix
  
import java.util.*;
  
public class GFG {
  
    public void Boundary_Elements(int mat[][])
    {
        // Printing Input Matrix;
        System.out.println("Input Matrix is : ");
  
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
  
                System.out.print(mat[i][j]);
            }
  
            System.out.println();
        }
  
        // Printing Boundary Values of Matrix
        System.out.println("Resultant Matrix is :");
  
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
  
                if (i == 0 || j == 0 || i == mat.length - 1
                    || j == mat[i].length - 1) {
                    System.out.print(mat[i][j]);
                }
                else {
                    // Printing Space if element
                    // is not at Boundary
                    System.out.print(" ");
                }
            }
  
            System.out.println();
        }
    }
    public static void main(String[] args)
    {
        // Input Matrix
        int mat[][] = new int[][] { { 1, 2, 3 },
                                    { 4, 5, 6 },
                                    { 7, 8, 9 } };
  
        GFG B_Values = new GFG();
  
        B_Values.Boundary_Elements(mat);
    }
}


Output

Input Matrix is : 
123
456
789
Resultant Matrix is :
123
4 6
789

Time Complexity: O(N × M), where n and m are the dimensions of the matrix.

Space Complexity: O(N × M).

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS