Bird
0
0

Which of the following Swift code snippets correctly demonstrates a repeat-while loop that prints numbers from 1 to 3?

easy📝 Syntax Q3 of 15
Swift - Loops
Which of the following Swift code snippets correctly demonstrates a repeat-while loop that prints numbers from 1 to 3?
Avar i = 1 repeat { print(i) i += 1 } while i <= 3
Bvar i = 1 while i <= 3 { print(i) i += 1 }
Cvar i = 1 repeat { print(i) i += 1 } while i < 1
Dvar i = 1 repeat { print(i) i += 1 } while i == 1
Step-by-Step Solution
Solution:
  1. Step 1: Understand the repeat-while loop

    A repeat-while loop executes the block first, then checks the condition.
  2. Step 2: Analyze each option

    var i = 1 repeat { print(i) i += 1 } while i <= 3 correctly initializes i to 1, prints i, increments it, and continues while i is less than or equal to 3, printing 1, 2, 3.
    var i = 1 while i <= 3 { print(i) i += 1 } uses a while loop, not repeat-while.
    var i = 1 repeat { print(i) i += 1 } while i < 1's condition i < 1 is false after first iteration, so it only prints once.
    var i = 1 repeat { print(i) i += 1 } while i == 1's condition i == 1 is false after first increment, so it only prints once.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    repeat-while runs at least once and checks condition after loop body [OK]
Quick Trick: repeat-while checks condition after executing loop body [OK]
Common Mistakes:
  • Confusing repeat-while with while loop syntax
  • Placing condition before loop body
  • Using incorrect comparison operators in condition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes