LearnFrenzy
Sign in Take a free test

Control Flow Statements · Predict the Output · Question 9

break inside a nested loop Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == i) break;          // leaves only the inner loop
                count++;
            }
        }
        System.out.println(count);
    }
}
  • A 3 Correct
  • B 9
  • C 6
  • D 0
Correct Answer: Option A

For i = 1 the inner loop breaks at once (0); for i = 2 it counts j = 1 (1); for i = 3 it counts j = 1, 2 (2). Total 3.

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