Bird
0
0

Find the mistake in this Swift code:

medium📝 Debug Q7 of 15
Swift - Loops
Find the mistake in this Swift code:
var count = 1
repeat {
    print(count)
    count += 1
} while count < 5
print(count)
ANo mistake; code runs correctly.
BThe loop condition should be 'count <= 5'.
CThe print after the loop is unreachable.
DVariable count should be declared inside the loop.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop behavior

    The loop runs while count is less than 5, printing 1 to 4.
  2. Step 2: Check code after loop

    After loop ends, count is 5, and the print(count) outside prints 5 correctly.
  3. Final Answer:

    No mistake; code runs correctly. -> Option A
  4. Quick Check:

    Code runs without errors or unreachable code [OK]
Quick Trick: Code after repeat-while runs after loop ends [OK]
Common Mistakes:
  • Thinking print after loop is unreachable
  • Changing condition unnecessarily
  • Declaring variables inside loop unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes