Control Flow
For Ranges
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
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)
}
}
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) {total ← 1
pass 1 of 46for (number1 <- 1 to end4) {7 total→ 1 = total + number18}All 4 passes — pass 1 is the card above pass numbertotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 println("end=" + end)
10 println("end=" + end4)11 println("total=" + total10)12 }13}outputend=4 total=10
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) {total ← 1
pass 1 of 26for (number1 <- 1 to end2) {7 total→ 1 = total + number18}total ← 3
pass 2 of 26for (number2 <- 1 to end2) {7 total→ 3 = total + number28}println("end=" + end)
10 println("end=" + end2)11 println("total=" + total3)12 }13}outputend=2 total=3
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) {total ← 1
pass 1 of 56for (number1 <- 1 to end5) {7 total→ 1 = total + number18}All 5 passes — pass 1 is the card above pass numbertotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 println("end=" + end)
10 println("end=" + end5)11 println("total=" + total15)12 }13}outputend=5 total=15
Follow the Range
endstarts at4.totalstarts at0.- The loop visits
1,2,3, and4. - Each number is added to
total, ending at10. - The program prints
end=4andtotal=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.