Menu
Coddy logo textTech

Nested Loop

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 52 of 93.

You can place a loop inside another loop to create a nested loop. The inner loop runs completely for each iteration of the outer loop.

for (i in 1..2) {
    for (j in 1..3) {
        println("i=$i, j=$j")
    }
}
// Output:
// i=1, j=1
// i=1, j=2
// i=1, j=3
// i=2, j=1
// i=2, j=2
// i=2, j=3

When i is 1, the inner loop runs three times (j goes from 1 to 3). Then i becomes 2, and the inner loop runs three more times. This gives us 2 × 3 = 6 total iterations.

Nested loops are commonly used to create patterns or work with grid-like structures:

for (row in 1..3) {
    for (col in 1..row) {
        print("*")
    }
    println()
}
// Output:
// *
// **
// ***

Here, the inner loop's range depends on the outer loop's variable, creating a triangle pattern. The print() function outputs without a newline, while println() moves to the next line after each row.

challenge icon

Challenge

Medium

Read an integer n from input. Use nested loops to print a multiplication table for numbers 1 through n.

For each row i from 1 to n, print the products i * 1, i * 2, ..., i * n separated by spaces, followed by a newline.

For example, if the input is 3, the output should be:

1 2 3
2 4 6
3 6 9

If the input is 4, the output should be:

1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16

Use print() with a space to output values on the same line, and println() to move to the next row.

Try it yourself

fun main() {
    // Read input
    val n = readLine()!!.toInt()
    
    // TODO: Write your code below
    // Use nested loops to print the multiplication table
    // Use print() with a space for values on the same line
    // Use println() to move to the next row
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground