C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Diagonal Array Program - Java Programs

Define a class to accept values into an integer array of order 4 × 4 and check whether it is a diagonal array or not. An array is diagonal if the sum of the left diagonal elements equals the sum of the right diagonal elements. Print the appropriate message.


Example:
3 4 2 5
2 5 2 3
5 3 2 7
1 3 7 1


Sum of the left diagonal elements = 3 + 5 + 2 + 1 = 11
Sum of the right diagonal elements = 5 + 2 + 3 + 1 = 11

import java.util.Scanner; class Diagonal{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int mat[][] = new int[4][4]; System.out.println("Enter matrix elements:"); int left = 0; int right = 0; for(int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ mat[i][j] = Integer.parseInt(in.nextLine()); if(i == j) left += mat[i][j]; if(i + j == 3) right += mat[i][j]; } } if(left == right) System.out.println("Diagonal matrix!"); else System.out.println("Not a diagonal matrix."); } }

Output

 
 OUTPUT : 
Enter matrix elements:
3
4
2
5
2
5
2
3
5
3
2
7
1
3
7
1
Diagonal matrix!