Kotlin - for Loop Examples



This post shows you how to loop or iterate an array using for loop examples. The for loop provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied.

Kotlin- for Loop Examples

Refer the comments are self-descriptive.
package net.javaguides.kotlin

fun main(args: Array < String > ) {

    // For loop - iterating through a range
    for (value in 1. .10) {
        print("$value ")
    }

    // Iterating through an array
    var primeNumbers = intArrayOf(2, 3, 5, 7, 11)

    for (number in primeNumbers) {
        print("$number ")
    }

    // Iterating through an array using indices

    primeNumbers = intArrayOf(2, 3, 5, 7, 11)

    for (index in primeNumbers.indices) {
        println("PrimeNumber(${index+1}): ${primeNumbers[index]}")
    }


    // Retrieve array index and element in each iteration using withIndex()

    primeNumbers = intArrayOf(2, 3, 5, 7, 11)

    for ((index, number) in primeNumbers.withIndex()) {
        println("PrimeNumber(${index+1}): $number")
    }
}
Output:
1 2 3 4 5 6 7 8 9 10 2 3 5 7 11 PrimeNumber(1): 2
PrimeNumber(2): 3
PrimeNumber(3): 5
PrimeNumber(4): 7
PrimeNumber(5): 11
PrimeNumber(1): 2
PrimeNumber(2): 3
PrimeNumber(3): 5
PrimeNumber(4): 7
PrimeNumber(5): 11

Comments