Kotlin cycle control


Release date:2023-09-22 Update date:2023-10-13 Editor:admin View counts:255

Label:

Kotlin cycle control

For cycle

for loop can provide an iterator for any iterator syntax isas follows:

for (item in collection) print(item)

The body of the loop can be a code block:

for (item: Int in ints) {
    // ……
}

As mentioned above for you can loop through any object that provides aniterator.

If you want to traverse an array or an list you can do this:

for (i in array.indices) {
    print(array[i])
}

Note that this “traversal on the interval” is compiled into an optimized implementation without creating additional objects.

Or you can use library functions withIndex :

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

Example

Iterate over the collection:

fun main(args: Array<String>) {
    val items = listOf("apple", "banana", "kiwi")
    for (item in items) {
        println(item)
    }

    for (index in items.indices) {
        println("item at $index is ${items[index]}")
    }
}

Output result:

apple
banana
kiwi
item at 0 is apple
item at 1 is banana
item at 2 is kiwi

While and do…while cycle

while is the most basic loop, and its structure is:

While (Boolean expression) {
  //Circular Content
}

do…while loop for while statement, you cannot enter a loop if the condition is not met. But sometimes we need to execute at least once, even if the conditions are not met.

do…while cyclic and while cycle is similar, except that do…while loop is executed at least once.

do {
       //code statement
}While (Boolean expression);

Example

fun main(args: Array<String>) {
    println("----while use-----")
    var x = 5
    while (x > 0) {
        println( x--)
    }
    println("----do...while use-----")
    var y = 5
    do {
        println(y--)
    } while(y>0)
}

Powered by TorCMS (https://github.com/bukun/TorCMS).