Course Content
KOTLIN Tutorial
About Lesson

Loops (for, while)

In the world of programming, loops play a crucial role in executing repetitive tasks efficiently. Kotlin, a modern programming language, offers two main types of loops: for and while. Let’s delve into each loop type and explore how they can be effectively used in Kotlin.

1. For Loops in Kotlin

The for loop in Kotlin is versatile and can iterate over various types of data structures, making it a powerful tool for handling collections.

for (item in collection) {
// Code to be executed for each item in the collection
}

This loop simplifies the process of iterating over arrays, ranges, or any other iterable object. It’s concise and expressive, contributing to Kotlin’s reputation for readability.

2. While Loops in Kotlin

The while loop is another essential construct in Kotlin, allowing you to repeatedly execute a block of code as long as a given condition is true.

while (condition) {
// Code to be executed while the condition is true
}

This loop type is useful when the number of iterations is unknown beforehand. It’s crucial to ensure that the condition eventually becomes false to prevent an infinite loop.

3. Looping Through Collections

One of the strengths of Kotlin is its concise syntax for iterating through collections. The combination of for loops and lambda expressions enhance the language’s expressiveness.

val numbers = listOf(1, 2, 3, 4, 5)

numbers.forEach { number ->
// Code to be executed for each number in the list
}

This example uses the forEach function, which is a concise and readable way to loop through elements in a collection.

4. Breaking and Continuing

In Kotlin loops, you can exit a loop prematurely and continue skip the rest of the current iteration, and move to the next one. This provides flexibility in controlling the flow of your program.

for (i in 1..10) {
if (i == 5) {
break // Exit the loop when i is 5
}
// Code to be executed for each iteration
}

5. Nested Loops

Kotlin supports nested loops, allowing you to iterate over multiple levels of data structures. However, it’s essential to be mindful of the potential complexity that nested loops can introduce.

for (i in 1..3) {
for (j in 1..3) {
// Code to be executed for each combination of i and j
}
}