Loops repeat a block for each value in a range.

range loop A range like `1..limit` gives each integer from the start through the end.

Loops

limit
Loops.kt
Replay: real traced execution (multi-file project)
fun main() {
    val limit = 4
    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 = 6
    var total = 0

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

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

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

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

    9    println("limit=$limit4")10    println("total=$total10")11}
    outputlimit=4
    total=10
  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 ← 6, total ← 0

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

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

    9    println("limit=$limit6")10    println("total=$total21")11}
    outputlimit=6
    total=21

Follow the Loop

  1. limit starts at 4.
  2. total starts at 0.
  3. The loop visits 1, 2, 3, and 4.
  4. Each number is added to total.
  5. The program prints limit=4 and total=10. | limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |

Exercise: Loops.kt

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