Bird
0
0

What will be the output of the following Swift code?

medium📝 Predict Output Q4 of 15
Swift - Loops
What will be the output of the following Swift code?
var x = 1
repeat {
    print(x)
    x += 1
} while x < 4
ANo output
B1 2 3
C2 3 4
D1 2 3 4
Step-by-Step Solution
Solution:
  1. Step 1: Trace the loop iterations

    Initially, x = 1. The loop prints 1, then increments x to 2. Condition x < 4 is true, so loop repeats printing 2 and 3.
  2. Step 2: Check when loop stops

    After printing 3, x becomes 4. Condition x < 4 is false, so loop stops. Numbers printed: 1, 2, 3.
  3. Final Answer:

    1 2 3 -> Option B
  4. Quick Check:

    Output matches printed values 1 to 3 [OK]
Quick Trick: repeat-while runs until condition is false after loop body [OK]
Common Mistakes:
  • Including 4 in output
  • Starting output from 2
  • Thinking no output if condition false initially

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes