Foundations
Loops
Loops repeat a block for each value in a range.
range loop
A range like `1..limit` gives each integer from the start through the end.
Loops
Loops.kt
Replay: real traced execution (multi-file project)
fun main() {
val limit = 4
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 = 6
var total = 0
for (number in 1..limit) {
total += number
}
println("limit=$limit")
println("total=$total")
}
limit ← 4, total ← 0
1fun main() {2 val limit→ 4 = 4 //@limit=2, 63 var total→ 0 = 0total ← 1
pass 1 of 45for (number1 in 1..limit4) {6 total→ 1 += number17}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")
9 println("limit=$limit4")10 println("total=$total10")11}outputlimit=4 total=10
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 ← 6, total ← 0
1fun main() {2 val limit→ 6 = 63 var total→ 0 = 0total ← 1
pass 1 of 65for (number1 in 1..limit6) {6 total→ 1 += number17}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")
9 println("limit=$limit6")10 println("total=$total21")11}outputlimit=6 total=21
Follow the Loop
limitstarts at4.totalstarts at0.- The loop visits
1,2,3, and4. - Each number is added to
total. - The program prints
limit=4andtotal=10. | limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |
Exercise: Loops.kt
Reproduce total=10 for limit 4, then try limit 2 and 6 and predict each total before running it.