A while loop repeats while its condition remains true.

Repeat while true

limit
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)")
  1. limit ← 4, value ← 1, total ← 0

    1let limit→ 4 = 4  //@limit=2, 52var value→ 1 = 13var total→ 0 = 0
  2. total ← 1, value ← 2

    pass 1 of 4
    5while value1 <= limit4 {6    total→ 1 = total + value17    value→ 2 = value + 18}
    All 4 passes — pass 1 is the card above
    passtotalvalue
    10 11 2
    21 32 3
    33 63 4
    46 104 5
  3. print("limit=\(limit)")

    10print("limit=\(limit4)")11print("total=\(total10)")
    outputlimit=4
    total=10
  1. limit ← 2, value ← 1, total ← 0

    1let limit→ 2 = 22var value→ 1 = 13var total→ 0 = 0
  2. total ← 1, value ← 2

    pass 1 of 2
    5while value1 <= limit2 {6    total→ 1 = total + value17    value→ 2 = value + 18}
  3. total ← 3, value ← 3

    pass 2 of 2
    5while value2 <= limit2 {6    total→ 3 = total + value27    value→ 3 = value + 18}
  4. print("limit=\(limit)")

    10print("limit=\(limit2)")11print("total=\(total3)")
    outputlimit=2
    total=3
  1. limit ← 5, value ← 1, total ← 0

    1let limit→ 5 = 52var value→ 1 = 13var total→ 0 = 0
  2. total ← 1, value ← 2

    pass 1 of 5
    5while value1 <= limit5 {6    total→ 1 = total + value17    value→ 2 = value + 18}
    All 5 passes — pass 1 is the card above
    passtotalvalue
    10 11 2
    21 32 3
    33 63 4
    46 104 5
    510 155 6
  3. print("limit=\(limit)")

    10print("limit=\(limit5)")11print("total=\(total15)")
    outputlimit=5
    total=15

Add Up to the Limit

  1. limit starts at 4.
  2. value starts at 1.
  3. The loop runs while value <= limit.
  4. Each pass adds value, then increases it by 1.
  5. 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