Kotlin – Nested For Loop

Kotlin – Nested For Loop

In Kotlin, a nested for loop is a loop inside another loop. This allows you to iterate over elements in multiple dimensions, such as iterating over rows and columns in a matrix.

Examples

Example 1: Nested For Loop for Matrix

Let’s start with a simple example of using a nested for loop to iterate over elements in a matrix.

We’ll create a 2×3 matrix and print its elements using a nested for loop.

Kotlin Program

fun main() {
    // Define the matrix
    val matrix = arrayOf(
        intArrayOf(1, 2, 3),
        intArrayOf(4, 5, 6)
    )

    // Iterate over rows and columns using nested for loops
    for (row in matrix) {
        for (element in row) {
            print("$element ")
        }
        println()
    }
}

Output

1 2 3 
4 5 6 

Example 2: Nested For Loop for Multiplication Table

Another common use of nested for loops is to generate a multiplication table.

Here’s an example of generating a multiplication table up to 5×5.

Kotlin Program

fun main() {
    // Generate a multiplication table using nested for loops
    for (i in 1..5) {
        for (j in 1..5) {
            print("${i * j} ")
        }
        println()
    }
}

Output

1 2 3 4 5 
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 
5 10 15 20 25 

Summary

A nested for loop in Kotlin allows you to iterate over elements in multiple dimensions, such as iterating over rows and columns in a matrix or generating a multiplication table. It is a powerful tool for handling complex data structures and generating structured outputs.