Bird
0
0

How can you modify this nested loop to stop both loops when $i equals 2 and $j equals 3?

hard📝 Application Q9 of 15
PowerShell - Control Flow
How can you modify this nested loop to stop both loops when $i equals 2 and $j equals 3?
for ($i=1; $i -le 3; $i++) {
  for ($j=1; $j -le 5; $j++) {
    if ($i -eq 2 -and $j -eq 3) { break }
    Write-Output "$i,$j"
  }
}
AUse a labeled break with a loop label to exit both loops.
BReplace break with continue to skip the iteration.
CAdd a flag variable and check it after inner loop to break outer loop.
DUse multiple break statements, one for each loop.
Step-by-Step Solution
Solution:
  1. Step 1: Understand break behavior in nested loops

    Break only exits the innermost loop, so it won't stop the outer loop.
  2. Step 2: Use a labeled break with a loop label to exit both loops

    Prefix outer loop with :outer like :outer for ($i=1; $i -le 3; $i++) { for ($j=1; $j -le 5; $j++) { if ($i -eq 2 -and $j -eq 3) { break outer } Write-Output "$i,$j" } }.
  3. Final Answer:

    Use a labeled break with a loop label to exit both loops. -> Option A
  4. Quick Check:

    Labeled break for nested exit = C [OK]
Quick Trick: Use :outer before outer loop, break outer [OK]
Common Mistakes:
  • Expecting break to exit both loops
  • Using continue instead of break
  • Using multiple break statements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes