How to print the boundary elements of an array in java?

The blog provides the technical approach on ” How to print the boundary elements of an array in java? “

Problem Statement: 

How to print the Two Dimensional Arrays boundary elements in java? “

package com.java.planforexams.array;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
public class PrintArrayBoundaryElements {
	public static void main(String args[])throws IOException
	{
		int i,j,m,n;
		// Scanner object for reading User Input
		Scanner scan = new Scanner(System.in);
		// Enter Row Count
		System.out.print("Enter the Rows Count : ");
		 m= scan.nextInt();
		// Enter Column count
		System.out.print("Enter the Columns Count : ");
		 n= scan.nextInt();;
		//Creating the array
		int TwoDimensionalArray[][]=new int[m][n]; 
		for(i=0;i<m;i++)
		{
			for(j=0;j<n;j++)
			{
				System.out.println("Enter the array elements : ");
				TwoDimensionalArray[i][j]=scan.nextInt();
			}
		}
	System.out.println("Printing the Boundary elements of an Array:");
		for(i=0;i<m;i++)
		{
			for(j=0;j<n;j++)
			{
				// Print the Array Boundary elements when if condition is met
				if(i==0 || j==0 || i == m-1 || j == n-1) 
					System.out.print(TwoDimensionalArray[i][j]+"\t");
				else
					System.out.print(" \t");
			}
			System.out.println();
		}
	}
}

Output:
Enter the Rows Count : 3
Enter the Columns Count : 5
Enter the array elements : 
12
Enter the array elements : 
34
Enter the array elements : 
23
Enter the array elements : 
99
Enter the array elements : 
54
Enter the array elements : 
90
Enter the array elements : 
80
Enter the array elements : 
79
Enter the array elements : 
97
Enter the array elements : 
100
Enter the array elements : 
106
Enter the array elements : 
107
Enter the array elements : 
3
Enter the array elements : 
2
Enter the array elements : 
8
Printing the Boundary elements of an Array:
12	34	23	99	54	
90	 	 	 	100	
106	107	3	2	8	

Leave a Reply

Your email address will not be published. Required fields are marked *

*