Loop over a small range and accumulate a total.

loop A `for` loop repeats a block for each value in a range or collection.

For Loop

limit
ForLoop.kt
Replay: real traced execution (multi-file project)
fun main() {
    val limit = 3
    var total = 0

    for (number in 1..limit) {
        total += number
    }

    println("limit=$limit")
    println("total=$total")
}
fun main() {
    val limit = 2
    var total = 0

    for (number in 1..limit) {
        total += number
    }

    println("limit=$limit")
    println("total=$total")
}
fun main() {
    val limit = 5
    var total = 0

    for (number in 1..limit) {
        total += number
    }

    println("limit=$limit")
    println("total=$total")
}
  1. limit ← 3, total ← 0

    1fun main() {2    val limit→ 3 = 3 //@limit=2, 53    var total→ 0 = 0
  2. total ← 1

    pass 1 of 3
    5for (number1 in 1..limit3) {6    total→ 1 += number17}
    All 3 passes — pass 1 is the card above
    passnumbertotal
    110 1
    221 3
    333 6
  3. println("limit=$limit")

    9    println("limit=$limit3")10    println("total=$total6")11}
    outputlimit=3
    total=6
  1. limit ← 2, total ← 0

    1fun main() {2    val limit→ 2 = 23    var total→ 0 = 0
  2. total ← 1

    pass 1 of 2
    5for (number1 in 1..limit2) {6    total→ 1 += number17}
  3. total ← 3

    pass 2 of 2
    5for (number2 in 1..limit2) {6    total→ 3 += number27}
  4. println("limit=$limit")

    9    println("limit=$limit2")10    println("total=$total3")11}
    outputlimit=2
    total=3
  1. limit ← 5, total ← 0

    1fun main() {2    val limit→ 5 = 53    var total→ 0 = 0
  2. total ← 1

    pass 1 of 5
    5for (number1 in 1..limit5) {6    total→ 1 += number17}
    All 5 passes — pass 1 is the card above
    passnumbertotal
    110 1
    221 3
    333 6
    446 10
    5510 15
  3. println("limit=$limit")

    9    println("limit=$limit5")10    println("total=$total15")11}
    outputlimit=5
    total=15

Follow the Range

  1. limit starts as 3.
  2. The loop runs through 1..limit.
  3. That means the loop visits 1, 2, and 3.
  4. total adds each number.
  5. The script prints limit=3 and total=6. | number | running total | | --- | --- | | 1 | 1 | | 2 | 3 | | 3 | 6 |

Exercise: ForLoop.kt

Reproduce limit=3 and total=6, then use the pinned limit variants 2 and 5 to predict totals 3 and 15.