Loops in Kotlin - for and while


Loops are fundamental in programming, allowing you to repeat a block of code multiple times. In Kotlin, you have two primary loop constructs: for and while loops. In this guide, we'll explore how to use these loops in your Kotlin programs.


For Loop

The for loop is used for iterating over a range, a collection, or any other iterable object. Here's how you can use it:

for (i in 1..5) {
println("Iteration $i")
}

You can also iterate over arrays and lists:

val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}

While Loop

The while loop is used when you need to repeat a block of code while a condition is true:

var count = 0
while (count < 5) {
println("Count is $count")
count++
}

The condition is evaluated before each iteration, and the loop continues as long as the condition remains true.


Conclusion

Loops are essential tools for performing repetitive tasks in your Kotlin programs. Whether you're iterating over collections or executing code while a condition holds, for and while loops give you the flexibility to control program flow efficiently. As you explore Kotlin further, you'll find that loops are invaluable in various scenarios.


Happy coding!