Bird
0
0

Given the task to print all pairs (i, j) where i and j range from 1 to 3, but stop all loops immediately when i + j equals 4, which Swift code correctly uses labeled statements to achieve this?

hard📝 Application Q15 of 15
Swift - Loops
Given the task to print all pairs (i, j) where i and j range from 1 to 3, but stop all loops immediately when i + j equals 4, which Swift code correctly uses labeled statements to achieve this?
AouterLoop: for i in 1...3 { for j in 1...3 { if i + j == 4 { break outerLoop } print("\(i),\(j)") } }
Bfor i in 1...3 { for j in 1...3 { if i + j == 4 { break } print(i, j) } }
CouterLoop: for i in 1...3 { for j in 1...3 { if i + j == 4 { continue outerLoop } print(i, j) } }
Dfor i in 1...3 { for j in 1...3 { if i + j == 4 { continue } print(i, j) } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the stopping condition

    We want to stop all loops immediately when i + j == 4, so we must break the outer loop.
  2. Step 2: Use labeled break correctly

    outerLoop: for i in 1...3 { for j in 1...3 { if i + j == 4 { break outerLoop } print("\(i),\(j)") } } uses 'break outerLoop' to stop the outer loop from inside the inner loop, which is correct.
  3. Step 3: Check other options

    for i in 1...3 { for j in 1...3 { if i + j == 4 { break } print(i, j) } } breaks only inner loop; C uses continue which skips iterations but doesn't stop loops; D continues inner loop only.
  4. Final Answer:

    Code that breaks outerLoop when i + j == 4 -> Option A
  5. Quick Check:

    Labeled break stops all loops = A [OK]
Quick Trick: Use labeled break to stop outer loop from inner loop [OK]
Common Mistakes:
  • Using break without label stops only inner loop
  • Using continue instead of break
  • Not labeling the outer loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes