C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Double Dimensional Array - Diagonal Sum - Java Programs

Question 9
Write a program to input and store integer elements in a double dimensional array of size 3 × 3 and find the sum of elements in the left diagonal.


Example:
1 3 5
4 6 8
9 2 4

Output:
Sum of the left diagonal elements = (1 + 6 + 4) = 11

import java.util.Scanner; class Matrix{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int a[][] = new int[3][3]; int sum = 0; System.out.println("Enter elements:"); for(int i = 0; i < a.length; i++){ for(int j = 0; j < a.length; j++){ a[i][j] = Integer.parseInt(in.nextLine()); if(i == j) sum += a[i][j]; } } System.out.println("Sum of the left diagonal elements = " + sum); } }

Output

 
 OUTPUT 1: 
Enter elements:
1
2
3
4
5
6
7
8
9
Sum of the left diagonal elements = 15 

 OUTPUT 2: 
Enter elements:
5
1
9
2
8
3
4
7
6
Sum of the left diagonal elements = 19