LearnFrenzy
Sign in Take a free test

Control Flow Statements · Predict the Output · Question 19

A while(true) loop with break Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 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 = 27, steps = 0, peak = n;
        while (true) {
            if (n == 1) break;
            n = (n % 2 == 0) ? n / 2 : 3 * n + 1;     // Collatz step
            peak = Math.max(peak, n);
            steps++;
        }
        System.out.println(steps + " " + peak);
    }
}
  • A 111 9232 Correct
  • B 112 9232
  • C 111 27
  • D 27 9232
Correct Answer: Option A

27 famously takes 111 steps to reach 1 under the Collatz rule, climbing as high as 9232.

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