Loops repeat a block of code. A for loop is a direct way to walk through a range of numbers.

Sum a range

limit
loops.swift
Replay: real traced execution (multi-file project)
let limit = 4
var total = 0

for value in 1...limit {
    total = total + value
}

print("limit=\(limit)")
print("total=\(total)")
let limit = 3
var total = 0

for value in 1...limit {
    total = total + value
}

print("limit=\(limit)")
print("total=\(total)")
let limit = 6
var total = 0

for value in 1...limit {
    total = total + value
}

print("limit=\(limit)")
print("total=\(total)")
  1. limit ← 4, total ← 0

    1let limit→ 4 = 4  //@limit=3, 62var total→ 0 = 0
  2. total ← 1

    pass 1 of 4
    4for value1 in 1...limit4 {5    total→ 1 = total + value16}
    All 4 passes — pass 1 is the card above
    passvaluetotal
    110 1
    221 3
    333 6
    446 10
  3. print("limit=\(limit)")

    8print("limit=\(limit4)")9print("total=\(total10)")
    outputlimit=4
    total=10
  1. limit ← 3, total ← 0

    1let limit→ 3 = 32var total→ 0 = 0
  2. total ← 1

    pass 1 of 3
    4for value1 in 1...limit3 {5    total→ 1 = total + value16}
    All 3 passes — pass 1 is the card above
    passvaluetotal
    110 1
    221 3
    333 6
  3. print("limit=\(limit)")

    8print("limit=\(limit3)")9print("total=\(total6)")
    outputlimit=3
    total=6
  1. limit ← 6, total ← 0

    1let limit→ 6 = 62var total→ 0 = 0
  2. total ← 1

    pass 1 of 6
    4for value1 in 1...limit6 {5    total→ 1 = total + value16}
    All 6 passes — pass 1 is the card above
    passvaluetotal
    110 1
    221 3
    333 6
    446 10
    5510 15
    6615 21
  3. print("limit=\(limit)")

    8print("limit=\(limit6)")9print("total=\(total21)")
    outputlimit=6
    total=21

Follow the Loop

  1. limit starts at 4.
  2. total starts at 0.
  3. The range 1...limit visits 1, 2, 3, and 4.
  4. Each value is added to total.
  5. The program prints limit=4 and total=10. | limit | values added | total | | --- | --- | --- | | 3 | 1, 2, 3 | 6 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |
closed range `1...limit` includes both endpoints.

Exercise: loops.swift

Reproduce total=10 for limit 4, then try limit 3 and 6 and predict each total before running it.