Loops in Kotlin
Placement-ready Courses: Enroll Now, Thank us Later!
Loops are fundamental constructs in programming languages that allow us to execute a block of code repeatedly. Kotlin provides several loop constructs, such as ‘for’, ‘while’, and ‘do-while’, which offer flexibility and control over the flow of execution. In this article, we will dive into these loop statements, understand their usage, and explore the ‘continue’ statement for more refined control within loops.
Loops in Kotlin
1. For Loop in Kotlin
The ‘for’ loop in Kotlin simplifies the process of iterating over a range, an array, or any other collection. It follows a concise syntax that enhances code readability. Let’s consider an example to showcase the usage of a ‘for’ loop.
fun main() {
val names = arrayOf("DataFlair", "Mugdha", "Madhu", "Kins")
for (name in names) {
println("Hello, $name!")
}
}
Output:
Hello, Mugdha!
Hello, Madhu!
Hello, Kins!
Explanation:
We define an array called `names` containing some names.
Using the ‘for’ loop, we iterate over each element in the `names` array, assigning the current element to the variable ‘name’.
Within the loop, we print a greeting message using the value of ‘name’ with string interpolation.
The output shows the greeting messages for each name in the array.
2. While Loop in Kotlin
The ‘while’ loop in Kotlin repeatedly executes a block of code as long as a given condition remains true. It offers flexibility when the number of iterations is unknown in advance. Here’s an example illustrating the usage of the ‘while’ loop.
fun main() {
var count = 0
while (count < 5) {
println("Count: $count")
count++
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Explanation:
We declare a variable named `count` and initialize it with 0.
The ‘while’ loop executes the block of code inside it as long as the condition `count < 5` is true.
Within the loop, we print the current value of `count` and then increment it by one.
The output shows the values of `count` from 0 to 4, as the loop iterates until the condition is no longer true.
3. Kotlin Do-While Loop:
The ‘do-while’ loop in Kotlin is similar to the ‘while’ loop, but it guarantees the execution of the loop block at least once, as the condition is checked at the end of the loop. Let’s explore a scenario using the ‘do-while’ loop.
fun main() {
var count = 5
do {
println("Count: $count")
count--
} while (count > 0)
}
Output:
Count: 4
Count: 3
Count: 2
Count: 1
Explanation:
We initialize the variable `count` with 5.
The ‘do-while’ loop executes the code block first and then checks the condition `count > 0`.
Within the loop, we print the current value of `count` and then decrement it by one.
The output shows the values of `count` from 5 to 1, as the loop iterates until the condition becomes false.
4. Continue Statement in Kotlin
The ‘continue’ statement in Kotlin allows you to skip the remaining code within a loop iteration and move to the next iteration immediately. This statement is handy when you want to skip certain iterations based on specific conditions. Let’s illustrate its usage.
fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
for (number in numbers) {
if (number % 2 == 0) {
continue
}
println("Odd number: $number")
}
}
Output:
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
Explanation:
We initialize an array called `numbers` with a range of values.
Using a ‘for’ loop, we iterate over each element in the `numbers` array.
Inside the loop, we use an ‘if’ condition to check if the current number is even.
If the number is even, the ‘continue’ statement skips the remaining code in the loop iteration and proceeds to the next iteration.
If the number is odd, we print a message indicating that it is an odd number.
The output shows the odd numbers in the `numbers` array, as the loop skips the even numbers using the ‘continue’ statement.
5. Use of ‘when’ inside the loop in Kotlin
The ‘when’ expression in Kotlin can be used inside loops for conditional branching. It allows you to match values and execute different code blocks based on the matched cases. Here’s an example:
fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
for (number in numbers) {
when (number) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
else -> println("Other")
}
}
}
Output:
Two
Three
Other
Other
Explanation:
We define an array called `numbers` containing some values.
Using a ‘for’ loop, we iterate over each element in the `numbers` array.
Inside the loop, we use the ‘when’ expression to match each number with specific cases and execute the corresponding code block.
If the number is 1, we print “One”. If it’s 2, we print “Two”. If it’s 3, we print “Three”. For any other number, we print “Other”.
The output shows the result of the ‘when’ expression for each number in the array.
6. Iterate Through a Range in Kotlin
Kotlin provides a convenient way to iterate through a range of values. A range is defined using the ‘..’ operator. Here’s an example:
fun main() {
for (i in 1..5) {
println(i)
}
}
Output:
2
3
4
5
Explanation:
We use a ‘for’ loop to iterate over the range `1..5`.
The loop iterates from the start value (1) to the end value (5), inclusive.
Within the loop, we print each value of `i`.
The output shows the values from 1 to 5, as the loop iterates through the range.
Different Ways to Iterate Through a Range in Kotlin
In Kotlin, you have flexibility in how you iterate through a range. You can specify the step value, iterate in reverse, or use exclusive end values. Let’s explore these variations.
1. Iterating with a step value in Kotlin
fun main() {
for (i in 1..10 step 2) {
println(i)
}
}
Output:
3
5
7
9
Explanation:
The range `1..10` is iterated with a step value of 2.
The loop starts at 1 and increments by 2 in each iteration.
We print each value of `i`.
The output shows the odd numbers from 1 to 9, as the loop skips every second value.
2. Iterating in reverse in Kotlin
fun main() {
for (i in 10 downTo 1) {
println(i)
}
}
Output:
9
8
7
6
5
4
3
2
1
Explanation:
The range `10 downTo 1` iterates in reverse order, from 10 to 1.
The loop decrements by 1 in each iteration.
We print each value of `i`.
The output shows the values from 10 to 1 in descending order.
3. Iterating with an exclusive end value in Kotlin
fun main() {
for (i in 1 until 5) {
println(i)
}
}
Output:
2
3
4
Explanation:
The range `1 until 5` iterates from 1 to 4.
The loop increments by 1 in each iteration.
We print each value of `i`.
The output shows the values from 1 to 4, as the loop iterates until the exclusive end value of 5.
7. Iterating Through an Array in Kotlin
You can use a ‘for’ loop to iterate through the elements of an array in Kotlin. Here’s an example:
fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
for (number in numbers) {
println(number)
}
}
Output:
2
3
4
5
Explanation:
We define an array called `numbers` containing some values.
Using a ‘for’ loop, we iterate over each element in the `numbers` array.
Within the loop, we print each element of the array.
The output shows the elements of the `numbers` array as the loop iterates through it.
8. Iterating Through a String in Kotlin
In Kotlin, a string can be treated as a collection of characters, allowing you to iterate through it using a ‘for’ loop. Here’s an example:
fun main() {
val message = "Hello"
for (char in message) {
println(char)
}
}
Output:
e
l
l
o
Explanation:
We define a string variable called `message` with the value “Hello”.
Using a ‘for’ loop, we iterate over each character in the `message` string.
Within the loop, we print each character of the string.
The output shows each character of the string as the loop iterates through it.
You cannot iterate through a range from top to down without using ‘downTo’:
By default, when iterating through a range in Kotlin, the loop starts from the lower value
and iterates up to the higher value. To iterate in reverse, from the higher value to the lower value, you need to use the ‘downTo’ keyword. Here’s an example:
fun main() {
for (i in 5..1) {
println(i)
}
}
Output:
(empty output)
Explanation:
In this example, we attempt to iterate through the range `5..1`.
Since we did not use the ‘downTo’ keyword, the loop does not execute, resulting in no output.
To iterate in reverse, we need to modify the code as follows:
fun main() {
for (i in 5 downTo 1) {
println(i)
}
}
Output:
4
3
2
1
Explanation:
By using the ‘downTo’ keyword, we specify that the loop should iterate from 5 down to 1.
The loop executes as expected, and we see the values from 5 to 1 printed in reverse order.
Iterating through a range from top to down with ‘downTo’ and step 3:
In Kotlin, you can combine the ‘downTo’ keyword with the ‘step’ keyword to iterate through a range in reverse order with a specific step value. Here’s an example:
fun main() {
for (i in 10 downTo 1 step 3) {
println(i)
}
}
Output:
7
4
1
Explanation:
We use the ‘downTo’ keyword to iterate from 10 down to 1.
The ‘step 3’ specifies that the loop should decrement by 3 in each iteration.
We print each value of `i`.
The output shows the values 10, 7, 4, and 1, as the loop iterates in reverse with a step of 3.
Traverse an array without using the index property:
In Kotlin, you can traverse an array without using the index property by directly accessing each element in the array. Here’s an example:
fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
for (number in numbers) {
println(number)
}
}
Output:
2
3
4
5
Explanation:
We define an array called `numbers` containing some values.
Using a ‘for’ loop, we iterate over each element in the `numbers` array.
Within the loop, we directly access and print each element of the array.
The output shows the elements of the `numbers` array as the loop traverses through it.
Traverse an array using the index property:
If you need to access both the elements and their indices while traversing an array, you can use the ‘indices’ property of the array in Kotlin. Here’s an example:
fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
for (index in numbers.indices) {
println("Index: $index, Element: ${numbers[index]}")
}
}
Output:
Index: 1, Element: 2
Index: 2, Element: 3
Index: 3, Element: 4
Index: 4, Element: 5
Explanation:
We define an array called `numbers` containing some values.
Using a ‘for loop’, we iterate over the indices of the `numbers` array using the `indices` property.
Within the loop, we access each element using the current index and print both the index and the element.
The output shows the indices and elements of the `numbers` array as the loop traverses through it.
Traverse a collection using a ‘for’ loop:
In Kotlin, you can use a ‘for’ loop to iterate through any collection, such as a list or set. The loop will iterate over each element in the collection. Here’s an example:
fun main() {
val colors = listOf("Red", "Green", "Blue")
for (color in colors) {
println(color)
}
}
Output:
Green
Blue
Explanation:
We define a list called `colors` containing some color names.
Using a ‘for’ loop, we iterate over each element in the `colors` list.
Within the loop, we print each color.
The output shows the color names in the `colors` list as the loop iterates through it.
Conclusion
Loops are powerful tools for controlling the flow of execution in Kotlin. They allow you to repeat a block of code multiple times, iterate through ranges, arrays, strings, and collections, and perform various operations based on specific conditions. By understanding the different loop constructs and their usage, you can write efficient and concise code in Kotlin.
Happy Coding! 🙂
We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

