A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/java-program-to-print-boundary-elements-of-the-matrix/ below:

Java Program to Print Boundary Elements of the Matrix

Java Program to Print Boundary Elements of the Matrix

Last Updated : 21 May, 2025

Try it on GfG Practice

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:

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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4