Question 17
Back to Exercise
What is the output of the following Java program?
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!