DEV Community

loizenai
loizenai

Posted on

Kotlin Loop: for loop + while loop + break & continue example

https://grokonez.com/kotlin/kotlin-loop-loop-loop-break-continue-example

Kotlin Loop: for loop + while loop + break & continue example

In the tutorial, Grokonez will show you how to work with Kotlin Loop statements: for, while, do while and break & continue with Kotlin loops.

I. Kotlin For loop

We use for statement to iterate through an iterator collection.

1. for statement with Array & List collection

The syntax is as follows:


for(item in anArray){
    println(item)
}

...
for(element in aList){
    println(element)
}

For working with index, we can use:

// with Array
for(i in anArray.indices){
    println("customer with index = $i is " + anArray[i])
}

... or ...
for((index, item) in anArray.withIndex()){
    println("the item at $index is $item")
}

// with List
for(index in aList.indices){
    println("element with index = $index is " + aList.get(index))
}

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

Practice:

More at:

https://grokonez.com/kotlin/kotlin-loop-loop-loop-break-continue-example

Kotlin Loop: for loop + while loop + break & continue example

Top comments (0)