A Simple program: Sum of Boundary elements of a Matrix
Write a program to accept a matrix of any size from the user an print the sum of the boundary elements of the matrix.
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.
Double Dimensional Array(Matrix) Program I (Maximum minimum element, sum, average)
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
To learn more about how to install Bluej watch the given video.
https://youtu.be/i845Tz5_QXU
Related Posts
Continue learning with these related articles

Logic Gates for ISC Class 11: Truth Tables, Universal Gates, Half and Full Adder
ISC Class 11 Computer Science notes on logic gates: AND, OR, NOT, NAND, NOR, XOR and XNOR with truth tables, why NAND and NOR are universal gates, and half adder and full adder circuits with their Boolean expressions.
Decimal to Binary Conversion in Java: 3 Programs with Examples
How to convert a decimal number to binary on paper and in Java: three programs (String, place value and Integer.toBinaryString), binary to decimal, a dry run and common mistakes.

ISC Class 11 Computer Science Sample Paper 2026-27 with Solutions
A full 70-mark ISC Class 11 Computer Science sample paper for the 2026-27 annual exam: MCQs, number systems, propositional logic, logic gates, Java classes, arrays, strings, searching and sorting, and computing ethics, with complete worked solutions.