LearnFrenzy
Sign in Take a free test

Control Flow Statements · Predict the Output · Question 20

Loop variables declared inside and outside the for Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        int i = 100;
        int found = -1;
        for (int k = 0; k < 10; k++) {
            if (k * k > 30) { found = k; break; }
        }
        for (i = 0; i < 3; i++) { }
        // k is not visible here; i keeps its last value
        System.out.println(found + " " + i);
    }
}
  • A 6 3 Correct
  • B 5 3
  • C 6 100
  • D 6 2
Correct Answer: Option A

6 × 6 = 36 is the first square above 30. The second loop reuses the outer i, which ends at 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