Open In App

Java Program to Print Boundary Elements of the Matrix

Last Updated : 21 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to learn how to print only the boundary elements of a given matrix in Java. Boundary elements mean the elements from the first row, last row, first column, and last column.

Example:

Input :
1 2 3
4 5 6
7 8 9

Output:
1 2 3
4 6
7 8 9


Now, let's understand the approach we are going to use in order to solve this problem.

Approach:

  • First, take the matrix as input from the user of N × M dimensions.
  • Iterate over the elements of the matrix with the help of nested loops.
  • For every element, check if it lies on the boundary or not.
  • We are going to print the element if it is in the first row (i == 0), last row (i == n-1), first column (j == 0), or last column (j == M-1).
  • Move to the next line after printing all columns of a row.

Let's now see the real implementation of this for better understanding

Example: Here, we are printing the boundary elements of a matrix.

Java
// Java Program to Print Boundary
// Elements of the Matrix
import java.util.*;

// Main class
public class Geeks {

    // Method to print boundary elements
    public void Boundary_Elements(int[][] mat) {
        
        // Printing the 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
        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 {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        
        // Input matrix
        int[][] mat = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Create object and call method
        Geeks obj = new Geeks();
        obj.Boundary_Elements(mat);
    }
}

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

Explanation: Here, the outer loop is traversing the matrix row wise and column wise and the condition inside the inner loop checks whether the current element lies on the boundary or not. If it lies on the boundary the element is printed otherwise the space will be printed and this way we can only print the boundary elements.

Time Complexity: The time complexity is O(N × M)
Space Complexity: The space complexity is O(1)

Note: Here, n and m are the dimensions of the matrix.



Next Article
Practice Tags :

Similar Reads