Foundations
Loops
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
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)
}
}
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) {total ← 1
pass 1 of 46for (number1 <- 1 to limit4) {7 total→ 1 += 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("limit=" + limit)
10 println("limit=" + limit4)11 println("total=" + total10)12 }13}outputlimit=4 total=10
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) {total ← 1
pass 1 of 26for (number1 <- 1 to limit2) {7 total→ 1 += number18}total ← 3
pass 2 of 26for (number2 <- 1 to limit2) {7 total→ 3 += number28}println("limit=" + limit)
10 println("limit=" + limit2)11 println("total=" + total3)12 }13}outputlimit=2 total=3
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) {total ← 1
pass 1 of 66for (number1 <- 1 to limit6) {7 total→ 1 += number18}All 6 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 6 6 15 → 21 println("limit=" + limit)
10 println("limit=" + limit6)11 println("total=" + total21)12 }13}outputlimit=6 total=21
What Happens
limitstarts at4.totalstarts at0.- The loop visits
1,2,3, and4. - Each number is added to
total. - The program prints
limit=4andtotal=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.