LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 7

Row and diagonal sums of a 2D array Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int diag = 0, anti = 0, last = 0;
        for (int i = 0; i < m.length; i++) {
            diag += m[i][i];
            anti += m[i][m.length - 1 - i];
        }
        for (int v : m[2]) last += v;
        System.out.println(diag + " " + anti + " " + last);
    }
}
  • A 15 15 24 Correct
  • B 15 15 18
  • C 12 15 24
  • D 15 18 24
Correct Answer: Option A

Main diagonal 1 + 5 + 9, anti-diagonal 3 + 5 + 7, last row 7 + 8 + 9.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links