Border elements of an array are placed at the border of the array. Which are satisfy some conditions (i)if row no = 0 or (total row -1) (ii) column no = 0 or (total col -1). Therefore, we just travel the array once and add all the elements which meet the above conditions.
import java.util.*;
public class Border2D
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
int s=0,m,n;
System.out.print("Enter the Row No :");
m=sc.nextInt();
System.out.print("Enter the Col No :");
n=sc.nextInt();
int [][]arr=new int[m][n];
for(int r=0;r<m;r++)
{
for(int c=0;c<n;c++)
{
arr[r][c]=sc.nextInt();
}
}
for(int r=0;r<m;r++)
{
for(int c=0;c<n;c++)
{
if((r==0) || (r==(m-1)) || (c==0) || (c==(n-1)))
{
s+=arr[r][c];
}
}
}
System.out.println("Sum Is : " + s);
}
}