Computer Applications

Let A(n x n) that are not diagonal array. Write a program to find the sum of all the elements which lie on either diagonal. For example, for the matrix shown below, your program should output 68 = (1 + 6 + 11 + 16 + 4 + 7 + 10 + 13):

Java

Java Arrays

7 Likes

Answer


public class KboatDDADiagonalSum
{
    public static void main(String args[]){
        
        int A[][] = {{1, 2, 3, 4} , 
                    {5, 6, 7, 8} , 
                    {9, 10, 11, 12} , 
                    {13, 14, 15, 16}};
        
        int sum = 0;
        for(int i = 0; i < 4; i++) {
            for(int j = 0; j < 4; j++) {
                if (i == j || (i + j) == 3) {
                    sum += A[i][j];
                }
            }
        }
        
        System.out.println("Sum of diagonal elements = " + sum);
        
    }
}

Variable Description Table

Program Explanation

Output

Answered By

2 Likes


Related Questions