Boundary elements are those elements which are not surrounded by elements on all four directions, i.e. elements in first row, first column, last row and last column.
To learn more about how to print the biggest(Maximum) and the smallest(Minimum) element of the array click the given link. https://wordpress-343193-1101484.cloudwaysapps.com/double-dimensional-arraymatrix-programs-part-i
Write a program to accept a matrix of any size from the user an print the sum of the boundary elements of the matrix.
import java.util.*;
public class Boundary_Elements
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int m, n, sum = 0, row1 = 0, col_n = 0, diag = 0;
System.out.print("\nEnter the no. of rows : ");
m = sc.nextInt();
System.out.print("\nEnter the no. of columns : ");
n = sc.nextInt();
int i, j;
int[][] mat = new int[m][n];
System.out.print("\n Input "+ m*n +" matrix elements \n");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
mat[i][j] = sc.nextInt();
}
}
System.out.println("The original matrix is");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
System.out.print(mat[i][j]+ " ");
}
System.out.println();
}
System.out.print("\n Boundary Matrix: \n");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
if (i == 0 || j == 0 || i == n-1|| j == n - 1)
{
System.out.print(mat[i][j] + " " );
sum = sum + mat[i][j];
}
else
System.out.print(" ");
}
System.out.println( );
}
System.out.print("\n Sum of boundary elements is " + sum);
}
}
Output :
Enter the no. of rows : 3
Enter the no. of columns : 3
Input 9 matrix elements
1
2
3
4
5
6
7
8
9
The matrix is
1 2 3
4 5 6
7 8 9
Boundary Matrix
1 2 3
4 6
7 8 9
Sum of boundary elements is 40