Control Flow
While Loop
A while loop repeats while its condition remains true.
Repeat while true
while_loop.swift
Replay: real traced execution (multi-file project)
let limit = 4
var value = 1
var total = 0
while value <= limit {
total = total + value
value = value + 1
}
print("limit=\(limit)")
print("total=\(total)")
let limit = 2
var value = 1
var total = 0
while value <= limit {
total = total + value
value = value + 1
}
print("limit=\(limit)")
print("total=\(total)")
let limit = 5
var value = 1
var total = 0
while value <= limit {
total = total + value
value = value + 1
}
print("limit=\(limit)")
print("total=\(total)")
limit ← 4, value ← 1, total ← 0
1let limit→ 4 = 4 //@limit=2, 52var value→ 1 = 13var total→ 0 = 0total ← 1, value ← 2
pass 1 of 45while value1 <= limit4 {6 total→ 1 = total + value17 value→ 2 = value + 18}All 4 passes — pass 1 is the card above pass totalvalue1 0 → 1 1 → 2 2 1 → 3 2 → 3 3 3 → 6 3 → 4 4 6 → 10 4 → 5 print("limit=\(limit)")
10print("limit=\(limit4)")11print("total=\(total10)")outputlimit=4 total=10
limit ← 2, value ← 1, total ← 0
1let limit→ 2 = 22var value→ 1 = 13var total→ 0 = 0total ← 1, value ← 2
pass 1 of 25while value1 <= limit2 {6 total→ 1 = total + value17 value→ 2 = value + 18}total ← 3, value ← 3
pass 2 of 25while value2 <= limit2 {6 total→ 3 = total + value27 value→ 3 = value + 18}print("limit=\(limit)")
10print("limit=\(limit2)")11print("total=\(total3)")outputlimit=2 total=3
limit ← 5, value ← 1, total ← 0
1let limit→ 5 = 52var value→ 1 = 13var total→ 0 = 0total ← 1, value ← 2
pass 1 of 55while value1 <= limit5 {6 total→ 1 = total + value17 value→ 2 = value + 18}All 5 passes — pass 1 is the card above pass totalvalue1 0 → 1 1 → 2 2 1 → 3 2 → 3 3 3 → 6 3 → 4 4 6 → 10 4 → 5 5 10 → 15 5 → 6 print("limit=\(limit)")
10print("limit=\(limit5)")11print("total=\(total15)")outputlimit=5 total=15
Add Up to the Limit
limitstarts at4.valuestarts at1.- The loop runs while
value <= limit. - Each pass adds
value, then increases it by1. - The total becomes
10. | Value | Running total | | --- | --- | |1|1| |2|3| |3|6| |4|10|
while
Use a `while` loop when the number of repetitions is controlled by changing state rather than by directly iterating over a collection.
Exercise: while_loop.swift
Use a while loop to add values from 1 through a limit and print the total