Bird
0
0

Identify the error in this Swift repeat-while loop code:

medium📝 Debug Q14 of 15
Swift - Loops
Identify the error in this Swift repeat-while loop code:
var x = 5
repeat {
    print(x)
    x += 1
} while x < 5
ANo error; the loop runs exactly once.
BThe loop will never run because condition is false initially.
CSyntax error: missing parentheses around condition.
DThe loop will run infinitely because x keeps increasing.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop condition and variable change

    Initial x is 5. The loop runs once before checking condition. Inside loop, x increases by 1 each time.
  2. Step 2: Check condition after first iteration

    After first iteration, x becomes 6. Condition is x < 5, which is false, so loop should stop. But since x increases, if condition was true, it would never stop. Here, it stops after one iteration.
  3. Step 3: Re-examine the condition logic

    Actually, since x starts at 5, condition x < 5 is false, so loop runs once then stops. No infinite loop.
  4. Final Answer:

    No error; the loop runs exactly once. -> Option A
  5. Quick Check:

    Loop runs once then stops [OK]
Quick Trick: Check variable change and condition carefully to avoid infinite loops [OK]
Common Mistakes:
  • Assuming infinite loop without checking condition
  • Thinking condition needs parentheses
  • Believing loop won't run at all

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes