Given a matrix of custom size the task is to print the boundary elements.
Example: Consider a matrix:-
| 1 | 4 | 5 | 7 |
| 3 | 2 | 2 | 8 |
| 5 | 6 | 1 | 9 |
Here boundary elements are 1, 4, 5, 7, 8, 9, 1, 6, 5, 3.
Java
import java.util.*;
public class PrintBoundaryElements
{
public static void main(String args[])
{
int row=0,col=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter no.of rows: ");
row=sc.nextInt();
System.out.print("Enter no.of columns: ");
col=sc.nextInt();
int ar[][]=new int[row][col];
System.out.println("Enter matrix elements:-");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
ar[i][j]=sc.nextInt();
}
}
System.out.print("Boundary elements are: ");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(i==0||i==row-1||j==0||j==col-1)
{
System.out.print(ar[i][j]+" ");
}
}
}
}
}Java