Computer Applications

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
2 5 2 3
5 3 2 7
1 3 7 1

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

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

Java

Java Arrays

ICSE 2024

9 Likes

Answer

import java.util.Scanner;

public class KboatDiagonalDDA
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int[][] arr = new int[4][4];
        
        System.out.println("Enter elements for 4x4 DDA:");
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                arr[i][j] = in.nextInt();
            }
        }
        
        int lSum = 0;
        int rSum = 0;
        
        for (int i = 0; i < 4; i++) {
            lSum += arr[i][i];
            rSum += arr[i][3 - i];
        }
        
        if (lSum == rSum) {
            System.out.println("The array is a DIAGONAL array.");
        } else {
            System.out.println("The array is NOT a DIAGONAL array.");
        }
    }
}

Variable Description Table

Program Explanation

Output

Answered By

2 Likes


Related Questions