Loop over a small numeric range.

for-range A for loop can visit each number in a range. The loop variable gets one value at a time.

For Ranges

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

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

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

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

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

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

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

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

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

    10    println("end=" + end4)11    println("total=" + total10)12  }13}
    outputend=4
    total=10
  1. end ← 2, total ← 0

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

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

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

    10    println("end=" + end2)11    println("total=" + total3)12  }13}
    outputend=2
    total=3
  1. end ← 5, total ← 0

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

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

    10    println("end=" + end5)11    println("total=" + total15)12  }13}
    outputend=5
    total=15

Follow the Range

  1. end starts at 4.
  2. total starts at 0.
  3. The loop visits 1, 2, 3, and 4.
  4. Each number is added to total, ending at 10.
  5. The program prints end=4 and total=10. | end | numbers visited | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 5 | 1, 2, 3, 4, 5 | 15 |

Exercise: ForRanges.scala

Reproduce total=10 for end 4, then try end 2 and end 5 and predict the total for each range.