Bird
0
0

What will be the output of this Swift code?

medium📝 Predict Output Q5 of 15
Swift - Loops
What will be the output of this Swift code?
var n = 5
while n > 0 {
    print(n * 2)
    n -= 2
}
A10 8 6 4 2
B10 6 2
C10 8 6
D10 8 4 2
Step-by-Step Solution
Solution:
  1. Step 1: Trace the loop values of n and printed output

    n=5 prints 10, n=3 prints 6, n=1 prints 2, then n=-1 stops loop.
  2. Step 2: List printed values

    Printed values are 10, 6, and 2.
  3. Final Answer:

    10 6 2 -> Option B
  4. Quick Check:

    Loop prints n*2 while n>0 = 10 6 2 [OK]
Quick Trick: Update loop variable correctly to avoid infinite loops [OK]
Common Mistakes:
  • Printing values when n is zero or negative
  • Forgetting to decrement n

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes