Basics

Kotlin Loops

Loop Structures

Kotlin loops use for and while with break and continue.

Introduction to Kotlin Loops

Loops in Kotlin help execute a block of code repeatedly, which is essential for tasks that require iteration. Kotlin provides two main types of loops: for and while. This guide will cover how these loops work and how you can control them using break and continue statements.

Using For Loops in Kotlin

The for loop in Kotlin is used to iterate over a range, array, or any other iterable object. The syntax is concise and easy to understand. Here's an example of iterating over a range of numbers:

In this example, the loop iterates from 1 to 5, printing each number. The .. operator creates a range inclusive of both ends.

Using While Loops in Kotlin

The while loop is used when you want to execute a block of code as long as a condition is true. Here's an example:

In this code snippet, the loop keeps running while i is less than or equal to 5. The value of i is incremented in each iteration.

The Break Statement

The break statement is used to exit a loop prematurely. This can be useful when you have found the result you were looking for and no longer need to continue the loop. Here's an example:

In this example, the loop will terminate when i equals 6. As a result, the numbers 1 through 5 will be printed.

The Continue Statement

The continue statement skips the current iteration of a loop and proceeds to the next iteration. Here's how you can use it:

In this code, the loop will skip printing the number 3 and will continue with the next iteration. Therefore, the output will be 1, 2, 4, 5.

Conclusion

Kotlin loops are powerful tools that allow you to perform repetitive tasks with ease. Understanding how to use for and while loops, along with break and continue statements, can significantly enhance your programming skills in Kotlin.

Previous
When