Given a matrix of custom size the task is to sum the boundary elements.
Example: Consider a matrix:-
| 11 | 4 | 5 | 7 |
| 3 | 10 | 2 | 13 |
| 5 | 6 | 11 | 9 |
Here sum boundary elements is 11+4+5+7+13+9+11+6+5+3 = 74.
The program should output only the sum of boundary elements.
Java
import java.util.*;
public class SumBoundaryElements
{
public static void main(String args[])
{
int row=0,col=0,sum=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();
}
}
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)
{
sum=sum+ar[i][j];
}
}
}
System.out.println("Sum of boundary elements is "+sum);
}
}Java