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

ISC Practical 2027: College Enrolment Code Validator and Stream Report – Algorithm and Java Program
Fully solved ISC Computer Science Practical 2027 question: validate college enrolment codes made of a stream, year and serial number, give the exact reason for each rejection, auto-correct lowercase streams and prepare a stream-wise report.

ISC Practical 2027: Digital Lock Security Code Analyzer – Algorithm and Java Program
Fully solved ISC Computer Science Practical 2027 number-logic question: for a 5 to 10 digit security code, find the first and last digits, odd and even position sums, product of non-zero digits, digit frequency and classify the code as STRONG, MODERATE or WEAK.

Boolean Algebra for ISC Class 12: Laws, Canonical SOP and POS, and Simplification
ISC Class 12 Computer Science notes on Boolean algebra: all the laws and theorems, duality, De Morgan's laws, minterms and maxterms, converting to canonical SOP and POS, and step-by-step algebraic simplification with solved examples.