0
0
Swiftprogramming~10 mins

Repeat-while loop in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Repeat-while loop
Start
Execute loop body
Check condition
Exit loop
The repeat-while loop runs the code inside first, then checks the condition. If true, it repeats; if false, it stops.
Execution Sample
Swift
var count = 1
repeat {
  print(count)
  count += 1
} while count <= 3
This code prints numbers 1 to 3 using a repeat-while loop.
Execution Table
Stepcount valueCondition (count <= 3)ActionOutput
11truePrint 1, count = 21
22truePrint 2, count = 32
33truePrint 3, count = 43
44falseExit loop
💡 count becomes 4, condition 4 <= 3 is false, so loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
count12344
Key Moments - 2 Insights
Why does the loop body run even when the condition is false at the start?
Because repeat-while checks the condition after running the loop body once, so the body always runs at least once (see execution_table step 1).
What happens if the condition is false right after the first loop execution?
The loop stops after that first execution, as shown in execution_table step 4 where condition is false and loop exits.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of count at step 3?
A4
B3
C2
D1
💡 Hint
Check the 'count value' column at step 3 in the execution_table.
At which step does the condition become false and the loop stops?
AStep 4
BStep 2
CStep 3
DStep 1
💡 Hint
Look at the 'Condition' column in execution_table and find where it is false.
If we change the condition to count < 3, how many times will the loop run?
A3 times
B1 time
C2 times
D4 times
💡 Hint
Refer to variable_tracker and think when count < 3 becomes false.
Concept Snapshot
repeat {
  // code to run
} while condition

- Runs loop body first, then checks condition
- Repeats while condition is true
- Always runs at least once
- Use when loop must run before condition check
Full Transcript
The repeat-while loop in Swift runs the code inside the loop first, then checks the condition. If the condition is true, it repeats the loop. If false, it stops. This means the loop body always runs at least once, even if the condition is false at the start. For example, with count starting at 1, the loop prints count and increases it by 1 each time. It stops when count becomes 4 because 4 <= 3 is false. The variable count changes from 1 to 4 through the loop. This loop is useful when you want to run code first and then decide if it should repeat.