In this tutorial you will learn about the Kotlin Loops and its application with practical example.
Kotlin Loops
In Kotlin, loops statements are used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. In Kotlin Programming Language we have following loops –
- Kotlin for loop
- Kotlin forEach statement
- Kotlin repeat statement
- Kotlin while loop
- Kotlin do..while loop
Kotlin for Loop
The for loop takes a collection of data(ranges, arrays, collections, or anything that provides an iterator) and iterate through the items one at a time in sequence.
Syntax:-
1 2 3 |
for (item in collection){ #statement(s) } |
Example:-
1 2 3 4 5 |
fun main(args : Array<String>) { for(value in 1..5) { println("$value ") } } |
Output:-
1 2 3 4 5 |
1 2 3 4 5 |
Kotlin while Loop
The while loop will execute a block of statement as long as a test expression is true.
Syntax:-
1 2 3 |
while(test_condition){ //loop body } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
// Program to print "Hello World!" 5 times fun main(args: Array<String>) { var i = 1 while (i <= 5) { println("Hello World!") ++i } } |
Output:-
1 2 3 4 5 |
Hello World Hello World Hello World Hello World Hello World |
Kotlin forEach statement
forEach can be used to repeat loop statement for each element in given collection.
Example:-
1 2 3 4 5 6 |
fun main(args: Array<String>) { var daysOfWeek = listOf("Sun","Mon","Tue","Wed","Thu","Fri","Sat") daysOfWeek.forEach{ println(it) } } |
Output:-
1 2 3 4 5 6 7 |
Sun Mon Tue Wed Thu Fri Sat |
Kotlin repeat statement
Kotlin repeat statement is used to execute a set of statements for N-number of times.
Example:-
The following program prints “Hello World!” 5 times
1 2 3 4 5 |
fun main(args: Array<String>) { repeat(5) { println("Hello World!") } } |
Output:-
1 2 3 4 5 |
Hello World! Hello World! Hello World! Hello World! Hello World! |
Kotlin do…while Loop
The do…while statement executes loop statements and then test the condition for next iteration and executes next only if condition is true.
Syntax:-
1 2 3 4 |
do{ //loop body } while(test_condition); |
Example:-
Let’s see a simple example of do-while loop printing “Hello World!” for 5 times.
1 2 3 4 5 6 7 8 |
fun main(args: Array<String>){ var i = 1 do { println("Hello World!") i++ } while (i<=5); } |
Output:-
1 2 3 4 5 |
Hello World! Hello World! Hello World! Hello World! Hello World! |