LearnFrenzy
Sign in Take a free test

Control Flow Statements · Predict the Output · Question 6

A while loop with a postfix decrement in its condition Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links