Loop statements in Kotlin
Loop statements are used to execute a block of statements repeatedly based on a condition or once for each element in a collection.
In this tutorial, we will list out different types of looping statements available in Kotlin, and examples for each of them.
The following tutorials explain looping statements in detail with syntax and a good range of examples.
Kotlin also provides some statements to break or continue the above loops.
The following tutorials cover some of the special use cases with loop statements.
Examples
In the following, we cover examples for each of the looping statements, break and continue statements.
1. For Loop Example – Iterate over elements of a list
In the following program, for loop is used to print each item of a list.
Main.kt
fun main(args: Array) {
var daysOfWeek = listOf("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
for(day in daysOfWeek){
println(day)
}
}
Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
2. While Loop Example – Print numbers from 1 to N
In this following program, we will use While Loop to print numbers from 1
to n
.
Main.kt
fun main() {
var n = 4
var i = 1
while(i <= n){
println(i)
i++
}
}
Output
1
2
3
4
3. Do-while Loop Example – Print numbers from 1 to N
In this following program, we will use Do-while Loop to print numbers from 1
to n
.
Main.kt
fun main() {
var n = 4
var i = 1
do {
println(i)
i++
} while(i <= n)
}
Output
1
2
3
4
Conclusion
In this Kotlin Tutorial – Kotlin Loops, we have learned different loop statements available in Kotlin programming, and how to use them to repeat of a specific set or block of statements in a loop.