Question 6
Back to Exercise
What is the output of the following Java program?
public class Main {
public static void main(String[] args) {
int n = 3;
while (n-- > 0) System.out.print(n + " ");
System.out.println("| " + n);
int m = 3;
while (--m > 0) System.out.print(m + " ");
System.out.println("| " + m);
}
}
- A 2 1 0 | -1 2 1 | 0 Correct
- B 3 2 1 | 0 2 1 | 0
- C 2 1 0 | 0 2 1 0 | 0
- D 2 1 | -1 2 1 | 0
Correct Answer: Option A
n-- compares the old value and decrements before the body; the final failing test also decrements, leaving -1. With --m, the decrement happens before the comparison.
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!