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 Kotlin, the main loop statements are for, while, and do-while. Kotlin also supports break and continue to control how a loop proceeds. This tutorial gives a practical overview of Kotlin loops with examples for collections, ranges, conditions, and loop-control statements.
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.
Kotlin Loop Types and When to Use Each One
Each Kotlin loop is suited for a different kind of repetition. Use a for loop when you already have a range, array, string, map, or collection to iterate. Use a while loop when repetition depends on a condition that must be checked before every iteration. Use a do-while loop when the block must run at least once before checking the condition.
| Kotlin loop | Best used for | Condition checked |
|---|---|---|
for | Iterating over ranges, arrays, strings, lists, maps, and other iterable objects | Based on the iterable or progression |
while | Repeating while a condition remains true | Before the loop body |
do-while | Running a block once, then repeating while a condition remains true | After the loop body |
break | Exiting a loop early | When the break statement is reached |
continue | Skipping the current iteration and moving to the next one | When the continue statement is reached |
Kotlin for Loop Syntax for Collections and Ranges
The Kotlin for loop iterates over anything that provides an iterator, such as a list, array, string, range, or progression.
for (item in collection) {
// statements to execute for each item
}
For numeric repetition, Kotlin commonly uses ranges and progressions instead of the classic Java-style for (i = 0; i < n; i++) loop.
for (i in 1..5) {
// 1, 2, 3, 4, 5
}
for (i in 0 until 5) {
// 0, 1, 2, 3, 4
}
for (i in 10 downTo 2 step 2) {
// 10, 8, 6, 4, 2
}
Kotlin Loop Examples for for, while and do-while
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
The variable day receives one value from daysOfWeek in each iteration. In modern Kotlin examples, fun main() is commonly used when command-line arguments are not needed.
Kotlin for Loop with Range, until, downTo and step
Kotlin ranges make numeric loops compact and readable. The range operator .. includes both ends, until excludes the upper end, downTo counts down, and step changes the increment.
Main.kt
fun main() {
for (i in 1..4) {
println("range: $i")
}
for (i in 0 until 4) {
println("until: $i")
}
for (i in 6 downTo 2 step 2) {
println("downTo step: $i")
}
}
Output
range: 1
range: 2
range: 3
range: 4
until: 0
until: 1
until: 2
until: 3
downTo step: 6
downTo step: 4
downTo step: 2
Use until when you want index-style loops from 0 up to, but not including, a size value. This is common when working with arrays and lists.
Kotlin for Loop with List Indices and withIndex
When you need both the index and the value from a list, Kotlin provides indices and withIndex(). Use withIndex() when you want the index and value together in a clean form.
Main.kt
fun main() {
val names = listOf("Arun", "Bala", "Charu")
for (index in names.indices) {
println("$index = ${names[index]}")
}
for ((index, name) in names.withIndex()) {
println("$index - $name")
}
}
Output
0 = Arun
1 = Bala
2 = Charu
0 - Arun
1 - Bala
2 - Charu
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
The while loop checks i <= n before each iteration. If the condition is false before the first iteration, the loop body does not run even once.
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
The do-while loop checks the condition after the loop body. Therefore, the body runs at least once even when the condition is false after the first execution.
The following example demonstrates this difference.
Main.kt
fun main() {
var count = 5
do {
println("Executed once")
count++
} while (count < 5)
}
Output
Executed once
Kotlin break and continue in Loop Statements
The break statement exits the nearest loop. The continue statement skips the rest of the current iteration and moves to the next iteration.
Main.kt
fun main() {
for (i in 1..6) {
if (i == 2) {
continue
}
if (i == 5) {
break
}
println(i)
}
}
Output
1
3
4
Here, 2 is skipped because of continue. The loop stops before printing 5 because of break.
Kotlin Labeled break and continue in Nested Loops
In nested loops, break and continue normally affect the nearest enclosing loop. Kotlin labels can be used when you need to control an outer loop directly.
Main.kt
fun main() {
outer@ for (row in 1..3) {
for (column in 1..3) {
if (row == 2 && column == 2) {
break@outer
}
println("row=$row, column=$column")
}
}
}
Output
row=1, column=1
row=1, column=2
row=1, column=3
row=2, column=1
The label outer@ is attached to the outer loop. The statement break@outer exits that outer loop, not just the inner loop.
Kotlin Loop Checklist for Correct Code
Use this checklist when reviewing loop statements in Kotlin programs.
- Use
forwhen iterating over a known collection, range, array, string, or map. - Use
whilewhen the number of iterations depends on a condition that may be false at the start. - Use
do-whileonly when the loop body must execute at least once. - Use
untilfor index loops where the upper bound should be excluded. - Update the loop variable inside
whileanddo-whileloops to avoid accidental infinite loops. - Use labels carefully in nested loops and keep label names meaningful.
Kotlin Loops FAQ
What are the loop statements available in Kotlin?
Kotlin provides for, while, and do-while loop statements. It also provides break and continue to control loop execution.
Does Kotlin have a Java-style for loop?
No. Kotlin does not use the classic Java-style for (initialization; condition; update) syntax. Kotlin uses for (item in iterable) with collections, ranges, arrays, strings, and progressions.
What is the difference between while and do-while loops in Kotlin?
A while loop checks the condition before running the loop body, so it may run zero times. A do-while loop runs the body first and checks the condition after that, so it runs at least once.
How do I loop from 0 to list size minus 1 in Kotlin?
You can use for (i in 0 until list.size) or for (i in list.indices). The indices form is usually clearer when the loop is tied directly to a list or array.
How do break and continue work in Kotlin loops?
break exits the nearest loop. continue skips the remaining statements in the current iteration and moves to the next iteration. In nested loops, labels such as break@outer can be used to target an outer loop.
Summary of Kotlin Loop Statements
In this Kotlin Tutorial – Kotlin Loops, we have learned different loop statements available in Kotlin programming, and how to use them to repeat a specific set or block of statements in a loop. Use for for collections and ranges, while for condition-based repetition, and do-while when the block must run at least once. For official language details, see the Kotlin documentation on control flow.
TutorialKart.com