Bird
0
0

Which of the following shows the correct way to write a while loop in Swift that prints numbers from 1 to 3?

easy📝 Syntax Q3 of 15
Swift - Loops
Which of the following shows the correct way to write a while loop in Swift that prints numbers from 1 to 3?
Avar i = 1 while i <= 3 { print(i) i += 1 }
Bwhile (i = 1; i <= 3; i++) { print(i) }
Cvar i = 1 while i < 3 { print(i) }
Dwhile i <= 3 { print(i) i += 1 }
Step-by-Step Solution
Solution:
  1. Step 1: Initialize the loop variable

    Set var i = 1 before the loop.
  2. Step 2: Write the while condition

    Use while i <= 3 to loop until 3.
  3. Step 3: Update the loop variable inside the loop

    Increment i by 1 each iteration with i += 1.
  4. Final Answer:

    var i = 1 while i <= 3 { print(i) i += 1 } correctly uses Swift syntax for a while loop.
  5. Quick Check:

    Initialization, condition, and increment inside loop [OK]
Quick Trick: Initialize, check condition, update variable inside loop [OK]
Common Mistakes:
  • Using C-style for loop syntax in Swift
  • Not initializing the loop variable before the loop
  • Missing increment inside the loop causing infinite loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes