Sum of left diagonal and right diagonal
Write a program to accept a two dimensional array(Square matrix) and calculate the sum of left and right diagonals.
Write a program to accept a two dimensional array(Square matrix) and calculate the sum of left and right diagonals.
import java.util.Scanner;
public class LeftRightDiagonal
{
public static void main()
{
int i,j,ld=0,rd=0;
Scanner sc=new Scanner(System.in);
System.out.println("enter size of rows & colums");
int r=sc.nextInt();
int c=r;
int arr[][]=new int[r][c];
int k=r-1;
System.out.println("enter the numbers");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
arr[i][j]=sc.nextInt();
}
}
System.out.println("The matrix is ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
for(i=0;i<r;i++)
{
ld=ld+arr[i][i];
}
for(i=0;i<c;i++)
{
rd=rd+arr[i][k];
k=k-1;
}
System.out.println("Sum of left diagonal:"+ld);
System.out.println("Sum of right diagonal:"+rd);
}
}Sample output:-
Enter size of rows & colums
3
enter the numbers
1
2
3
4
5
6
7
8
9
The matrix is
1 2 3
4 5 6
7 8 9
Sum of left diagonal:15
Sum of right diagonal:15
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.