Bird
0
0

Find the problem in this Swift code:

medium📝 Debug Q7 of 15
Swift - Loops
Find the problem in this Swift code:
var i = 0
while i < 5 {
    if i == 2 {
        break
    }
    print(i)
}
ABreak statement is used incorrectly.
BVariable i is never incremented, causing an infinite loop.
CPrint statement is outside the loop.
DNo problem; code runs fine.
Step-by-Step Solution
Solution:
  1. Step 1: Check loop control variable

    Variable i is initialized but never incremented inside the loop.
  2. Step 2: Understand effect on loop

    Since i stays 0, condition i < 5 is always true, causing infinite loop.
  3. Final Answer:

    Variable i is never incremented, causing an infinite loop. -> Option B
  4. Quick Check:

    Loop variable must change to avoid infinite loop [OK]
Quick Trick: Always update loop variable to avoid infinite loops [OK]
Common Mistakes:
  • Forgetting to increment loop variable
  • Misusing break statement
  • Misplacing print statement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes