Control Flow
For Loop
Loop over a small range and accumulate a total.
loop
A `for` loop repeats a block for each value in a range or collection.
For Loop
ForLoop.kt
Replay: real traced execution (multi-file project)
fun main() {
val limit = 3
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 = 5
var total = 0
for (number in 1..limit) {
total += number
}
println("limit=$limit")
println("total=$total")
}
limit ← 3, total ← 0
1fun main() {2 val limit→ 3 = 3 //@limit=2, 53 var total→ 0 = 0total ← 1
pass 1 of 35for (number1 in 1..limit3) {6 total→ 1 += number17}All 3 passes — pass 1 is the card above pass numbertotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 println("limit=$limit")
9 println("limit=$limit3")10 println("total=$total6")11}outputlimit=3 total=6
limit ← 2, total ← 0
1fun main() {2 val limit→ 2 = 23 var total→ 0 = 0total ← 1
pass 1 of 25for (number1 in 1..limit2) {6 total→ 1 += number17}total ← 3
pass 2 of 25for (number2 in 1..limit2) {6 total→ 3 += number27}println("limit=$limit")
9 println("limit=$limit2")10 println("total=$total3")11}outputlimit=2 total=3
limit ← 5, total ← 0
1fun main() {2 val limit→ 5 = 53 var total→ 0 = 0total ← 1
pass 1 of 55for (number1 in 1..limit5) {6 total→ 1 += number17}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("limit=$limit")
9 println("limit=$limit5")10 println("total=$total15")11}outputlimit=5 total=15
Follow the Range
limitstarts as3.- The loop runs through
1..limit. - That means the loop visits
1,2, and3. totaladds each number.- The script prints
limit=3andtotal=6. | number | running total | | --- | --- | | 1 | 1 | | 2 | 3 | | 3 | 6 |
Exercise: ForLoop.kt
Reproduce limit=3 and total=6, then use the pinned limit variants 2 and 5 to predict totals 3 and 15.