Loop starts i=1, prints 1; i=2, prints 2; at i=3, break triggers and loop stops.
Step 2: Determine printed output
Only 1 and 2 are printed before break stops the loop.
Final Answer:
1 2 -> Option A
Quick Check:
Break at i=3 stops loop, output = 1 2 [OK]
Hint: Break stops loop before printing i=3, so output ends at 2 [OK]
Common Mistakes:
Assuming break prints 3
Ignoring break and printing all numbers
Confusing break with continue
4. Identify the error in this Java code snippet:
int i = 0;
while(i < 5)
if(i == 3)
break;
i++;
System.out.println(i);
medium
A. Missing braces causing incorrect loop behavior
B. break cannot be used inside while loops
C. Variable i is not initialized
D. System.out.println is outside the loop
Solution
Step 1: Analyze loop structure and indentation
Without braces, only the first statement after while is inside the loop; i++ runs outside the loop.
Step 2: Understand effect on loop
Because i++ is outside, i never increments inside loop, causing infinite loop or wrong behavior.
Final Answer:
Missing braces causing incorrect loop behavior -> Option A
Quick Check:
Braces needed to group loop statements [OK]
Hint: Always use braces to group multiple statements in loops [OK]
Common Mistakes:
Assuming break is invalid in while
Ignoring indentation and braces
Thinking i++ runs inside loop
5. You want to find the first number divisible by 7 in an array and stop searching after finding it. Which code snippet correctly uses break to achieve this?
int[] nums = {10, 13, 21, 28, 35};
int result = -1;
for(int n : nums) {
// Fill here
}
System.out.println(result);
hard
A. if(n % 7 == 0) { continue; result = n; }
B. if(n % 7 == 0) { break; result = n; }
C. if(n % 7 == 0) { result = n; continue; }
D. if(n % 7 == 0) { result = n; break; }
Solution
Step 1: Understand the goal
We want to assign the first divisible by 7 number to result and then stop the loop immediately.
Step 2: Check correct break usage
if(n % 7 == 0) { result = n; break; } assigns result first, then breaks to stop searching. This is correct.
Step 3: Analyze incorrect options
if(n % 7 == 0) { break; result = n; } breaks before assigning result, so result stays -1. Options A and D use continue which skips to the next iteration and loop continues.
Final Answer:
if(n % 7 == 0) { result = n; break; } -> Option D
Quick Check:
Assign then break to stop loop [OK]
Hint: Assign value before break to stop loop after finding it [OK]
Common Mistakes:
Breaking before assignment
Using continue instead of break
Not stopping loop after finding value
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.