Define a class to accept values into an integer array of order 4 x 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 Sum of the left diagonal elements = 3 + 5 + 2 + 1 = 11 2 5 2 3 Sum of the right diagonal elements = 5 + 2 + 3 + 1 = 11 5 3 2 7 1 3 7 1
Topic: Two-dimensional array — DIAGONAL array
Answer
import java.util.Scanner;
class Diagonal { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int a[][] = new int[4][4]; int left = 0, right = 0;
System.out.println("Enter the array elements"); for(int i = 0; i < 4; i++) for(int j = 0; j < 4; j++) a[i][j] = sc.nextInt();
for(int i = 0; i < 4; i++) { left = left + a[i][i]; right = right + a[i][4 - 1 - i]; }
System.out.println("Sum of the left diagonal elements = " + left); System.out.println("Sum of the right diagonal elements = " + right);
if(left == right) System.out.println("It is a DIAGONAL array"); else System.out.println("It is not a DIAGONAL array"); } }
The whole question turns on recognising the two diagonals by their index pattern — and once you see it, only a SINGLE loop is needed for both.
Left (principal) diagonal: row equals column, so the elements are a[0][0], a[1][1], a[2][2], a[3][3] — written a[i][i]. Right (secondary) diagonal: row plus column equals n - 1, so the elements are a[0][3], a[1][2], a[2][1], a[3][0] — written a[i][n-1-i]. Because both use the same i, one loop of four passes adds to both totals. Using nested loops with an if is also acceptable but does sixteen tests where four suffice.
Check with the sample: left = 3 + 5 + 2 + 1 = 11 and right = 5 + 2 + 3 + 1 = 11, so the array is DIAGONAL — exactly as the question states.
Note that both diagonals share the centre element in an odd-sized array; with 4 x 4 they do not overlap, so no adjustment is needed here.
a[][] int[4][4] - stores the 16 elements entered by the user left int - sum of the left (principal) diagonal elements right int - sum of the right (secondary) diagonal elements i, j int - loop variables for rows and columns sc Scanner - object used to read input