CodeBlanks Logo Icon CodeBlanks

Summary - Loops

Combine for, while and range to write a multiplication table.

Summary - Loops

In this summary you'll combine for, while and ranges to build a multiplication table. In previous lessons you learned:

  • counted loops with for (i in 1..5)
  • conditional loops with while
  • at-least-once loops with do-while
  • ranges with 1..5, until, downTo

We'll do two mini tasks: print a row of the multiplication table (for + range) and count down (while).

Practice 3 times table

Write a fun main(). Use a for (i in 1..5) loop to print println("3 x $i = ${3 * i}"). Output: 3 x 1 = 3, 3 x 2 = 6, ..., 3 x 5 = 15.

Starter code

Main.kt
fun main() {
    // 3 times table
}

Sample solution

Main.kt
fun main() {
    for (i in 1..5) {
        println("3 x $i = ${3 * i}")
    }
}

Expected output

3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15

Practice Count down with while

Write a fun main(). Assign 5 to var n. Use a while (n > 0) loop to print println(n) and decrease with n = n - 1 each step. The output should be 5, 4, 3, 2, 1.

Starter code

Main.kt
fun main() {
    // Count down
}

Sample solution

Main.kt
fun main() {
    var n = 5
    while (n > 0) {
        println(n)
        n = n - 1
    }
}

Expected output

5
4
3
2
1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which range counts 1 to 5 (5 inclusive)?

  • 1 until 5
  • 1..5 Correct answer
  • 5 downTo 1
  • 1..4

Explanation: 1..5 includes both ends: 1, 2, 3, 4, 5.

2 Complete the range

Question
for (i in 1____5) { println("3 x $i = ${3 * i}") }
Answer
for (i in 1..5) { println("3 x $i = ${3 * i}") }

Explanation: The 1..5 range counts 1 to 5 (5 inclusive).

All lessons in Beginner