In Kotlin, loops allow you to repeat a block of code multiple times. Whether you need to iterate over a list, execute code until a condition is met, or repeat an action a certain number of times, Kotlin provides several looping constructs to handle these situations. In this article, we’ll explore the different types of loops in Kotlin—for
, while
, and do-while
—and provide practical examples to help you understand their usage.
By the end of this guide, you’ll know when to use each loop and how to write loops that iterate over collections, ranges, and more.
1. for
Loop
The for
loop in Kotlin is used to iterate over ranges, collections (such as lists and arrays), or any other iterable objects. The loop iterates through each element in the sequence, executing the block of code for each element.
Syntax:
for (item in collection) {
// Code to execute for each item
}
Example 1: Iterating Over a Range
fun main() {
for (i in 1..5) {
println(i)
}
}
Output:
1
2
3
4
5
In this example, the for
loop iterates over the range from 1
to 5
(inclusive) and prints each value.
Example 2: Iterating Over a List
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}
}
Output:
Apple
Banana
Cherry
Here, the for
loop iterates over the fruits
list and prints each fruit.
Example 3: Using withIndex()
to Access Indices
You can use the withIndex()
function to iterate over both the index and the value of a list or array.
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
for ((index, fruit) in fruits.withIndex()) {
println("Item at index $index is $fruit")
}
}
Output:
Item at index 0 is Apple
Item at index 1 is Banana
Item at index 2 is Cherry
This method is useful when you need to access both the index and the value of the collection.
Example 4: Iterating Over a Map
You can iterate over a map using the for
loop by accessing both keys and values.
fun main() {
val map = mapOf(1 to "One", 2 to "Two", 3 to "Three")
for ((key, value) in map) {
println("Key: $key, Value: $value")
}
}
Output:
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
2. while
Loop
The while
loop continues to execute a block of code as long as the specified condition is true
. The condition is checked before the loop starts, making it a pre-condition loop.
Syntax:
while (condition) {
// Code to execute while the condition is true
}
Example 1: Basic while
Loop
fun main() {
var i = 1
while (i <= 5) {
println(i)
i++
}
}
Output:
1
2
3
4
5
In this example, the while
loop prints the value of i
as long as i
is less than or equal to 5. The variable i
is incremented after each iteration.
3. do-while
Loop
The do-while
loop is similar to the while
loop, but it checks the condition after executing the block of code, making it a post-condition loop. This ensures that the code is executed at least once, even if the condition is false
.
Syntax:
do {
// Code to execute
} while (condition)
Example 1: Basic do-while
Loop
fun main() {
var i = 1
do {
println(i)
i++
} while (i <= 5)
}
Output:
1
2
3
4
5
Here, the do-while
loop executes the block of code first, then checks the condition i <= 5
. The loop continues as long as the condition is true
.
Example 2: Condition Is False Initially
fun main() {
var i = 6
do {
println(i)
i++
} while (i <= 5)
}
Output:
6
In this case, the condition i <= 5
is false
from the start, but the do-while
loop still executes once because the condition is checked after the code block.
4. Breaking Out of Loops with break
The break
statement allows you to exit a loop prematurely. Once the break
statement is encountered, the loop terminates, and the program continues with the code following the loop.
Example: Using break
in a Loop
fun main() {
for (i in 1..10) {
if (i == 5) {
break // Exit the loop when i equals 5
}
println(i)
}
}
Output:
1
2
3
4
In this example, the loop terminates when i
equals 5 due to the break
statement.
5. Skipping Iterations with continue
The continue
statement allows you to skip the current iteration of the loop and proceed to the next iteration without exiting the loop entirely.
Example: Using continue
in a Loop
fun main() {
for (i in 1..5) {
if (i == 3) {
continue // Skip the rest of the loop when i equals 3
}
println(i)
}
}
Output:
1
2
4
5
Here, the loop skips printing the value 3
and continues with the next iteration.
Real-World Use Case: Summing Numbers
Let’s write a program that sums all numbers from 1 to 10 using a for
loop.
Example:
fun main() {
var sum = 0
for (i in 1..10) {
sum += i
}
println("Sum: $sum") // Output: Sum: 55
}
This loop iterates over the numbers from 1
to 10
, adding each number to sum
, and then prints the total sum.
Conclusion
Kotlin provides a variety of looping constructs that help you iterate over sequences, repeat actions, and control the flow of your programs. Whether you’re working with ranges, collections, or conditions, Kotlin’s for
, while
, and do-while
loops offer a simple and effective way to handle repetitive tasks.
- Use the
for
loop to iterate over ranges, lists, arrays, and other iterable collections. - Use the
while
loop when you want to repeat a block of code as long as a condition istrue
. - Use the
do-while
loop when you need to ensure that the block of code executes at least once. - Use
break
to exit a loop early andcontinue
to skip the current iteration.
Next up, we’ll explore the when
expression in Kotlin, a powerful alternative to if-else
chains. Stay tuned!