Different types of Loops in Kotlin with Examples

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.

Loops in Kotlin with Examples

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

for loop in Kotlin

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 :

 

forEach in Kotlin

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

forEach example kotlin program:

Output :

 

repeat statement in Kotlin

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

repeat statement Example :

Output :

 

while loop in Kotlin

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 :

 

do-while loop in Kotlin

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, we have learnt different types of statements that help in executing a block of statements in a loop repeatedly.