LearnFrenzy
Sign in Take a free test

Control Flow Statements · Predict the Output · Question 17

Classifying numbers with if and ternary Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        int pos = 0, neg = 0, zero = 0;
        for (int n : new int[]{3, -1, 0, 7, -5, 0, 2}) {
            if (n > 0) pos++;
            else if (n < 0) neg++;
            else zero++;
        }
        System.out.println(pos + " " + neg + " " + zero + " " + (pos > neg ? "more positive" : "not more positive"));
    }
}
  • A 3 2 2 more positive Correct
  • B 3 2 2 not more positive
  • C 4 2 1 more positive
  • D 3 3 1 more positive
Correct Answer: Option A

Exactly one branch of the else-if ladder runs for each number.

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