Kotlin Loops are important to program tasks(block of statements) that has be executed multiple number of times, or do an action on a list of items, or execute an action continuously until a breaking condition happens, etc.

Kotlin Loops with Examples

In this Kotlin Tutorial, we shall learn different Kotlin statements available to do looping with examples. Following is the list :


Kotlin for loop

Using for loop statement, you can loop over any collection that is iterable, or any range of elements.

for loop example kotlin program with list :

Output :


for loop example kotlin program with range :

Output :


for loop example kotlin program with access index of the element in the iterable :

Output :


Kotlin forEach

forEach can be used to repeat a set of statement for each element in an iterable.

forEach example kotlin program:

Output :


Kotlin repeat

repeat statement is used when a set of statements has to be executed N-number of times.

repeat statement Example :

Output :


Kotlin While loop

while statement is used to repeat a task, checking the condition priorly for each iteration before executing the iterative block.

while loop example kotlin program :

Output :


while loop example kotlin program using break statement :

Output :


Kotlin do-while loop

do-while loop is same as while loop, except the condition is not checked for the first time before executing the iterative block. Therefore it is guaranteed that the iterative block is executed atleast once.

do-while example kotlin program :

Output :


Conclusion :

In this Kotlin Tutorial – Kotlin Loops, we have learnt different types of statements that help in executing a block of statements in a loop repeatedly.