Loops repeat a block for each value in a range.

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

Loops

limit
Loops.scala
Replay: real traced execution (multi-file project)
object Main {
  def main(args: Array[String]): Unit = {
    val limit = 4
    var total = 0

    for (number <- 1 to limit) {
      total += number
    }

    println("limit=" + limit)
    println("total=" + total)
  }
}
object Main {
  def main(args: Array[String]): Unit = {
    val limit = 2
    var total = 0

    for (number <- 1 to limit) {
      total += number
    }

    println("limit=" + limit)
    println("total=" + total)
  }
}
object Main {
  def main(args: Array[String]): Unit = {
    val limit = 6
    var total = 0

    for (number <- 1 to limit) {
      total += number
    }

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

    1object Main {2  def main(args: Array[String]): Unit = {3    val limit→ 4 = 4 //@limit=2, 64    var total→ 0 = 056    for (number <- 1 to limit) {
  2. total ← 1

    pass 1 of 4
    6for (number1 <- 1 to limit4) {7  total→ 1 += number18}
    All 4 passes — pass 1 is the card above
    passnumbertotal
    110 1
    221 3
    333 6
    446 10
  3. println("limit=" + limit)

    10    println("limit=" + limit4)11    println("total=" + total10)12  }13}
    outputlimit=4
    total=10
  1. limit ← 2, total ← 0

    1object Main {2  def main(args: Array[String]): Unit = {3    val limit→ 2 = 24    var total→ 0 = 056    for (number <- 1 to limit) {
  2. total ← 1

    pass 1 of 2
    6for (number1 <- 1 to limit2) {7  total→ 1 += number18}
  3. total ← 3

    pass 2 of 2
    6for (number2 <- 1 to limit2) {7  total→ 3 += number28}
  4. println("limit=" + limit)

    10    println("limit=" + limit2)11    println("total=" + total3)12  }13}
    outputlimit=2
    total=3
  1. limit ← 6, total ← 0

    1object Main {2  def main(args: Array[String]): Unit = {3    val limit→ 6 = 64    var total→ 0 = 056    for (number <- 1 to limit) {
  2. total ← 1

    pass 1 of 6
    6for (number1 <- 1 to limit6) {7  total→ 1 += number18}
    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)

    10    println("limit=" + limit6)11    println("total=" + total21)12  }13}
    outputlimit=6
    total=21

What Happens

  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.

Loop Picture

| limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |

Exercise: Loops.scala

Reproduce total=10 for limit 4, then use the pinned limits 2 and 6 to predict each total.