In today’s tutorial, we will learn how to use Kotlin loops. Understanding the differences between for loop, while loop, and do while loop with simple examples. Loops are an important part of every programming language. Loops allow us to execute a block of code multiple times based on a certain condition.
Loops in Kotlin: For Loop, While Loop & Do While Loop Explained with Example
1. For loop in Kotlin: The for loop iterates over a range, collection, or array. For loop used when we want to print all the items without any certain condition.
Syntax:
1 2 3 4 5 |
for (item in collection) { // code to execute } |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
fun main() { val numbers = arrayOf(1, 2, 3, 4, 5, 7, 8, 9, 10) for (num in numbers) { println("Number: $num") } // Using a range for (i in 1..5) { println("Range value: $i") } } // Output Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Number: 7 Number: 8 Number: 9 Number: 10 Range value: 1 Range value: 2 Range value: 3 Range value: 4 Range value: 5 |
2. While loop in Kotlin: In a while loop we can pass a certain condition and until the condition becomes false it executes the code continuously.
Syntax:
1 2 3 4 5 |
while (condition) { // code to execute } |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun main() { var number = 1 while (number <= 5) { println("Item: $number") number++ } } // Output Item: 1 Item: 2 Item: 3 Item: 4 Item: 5 |
3. Do-while loop in Kotlin: The do-while loop is the same as a normal while loop, Even if the condition is false, the code will still run at least once due to this.
Syntax:
1 2 3 4 5 |
do { // code to execute } while (condition) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun main() { var num = 5 do { println("Number: $num") num++ } while (num <= 8) } // Output Number: 5 Number: 6 Number: 7 Number: 8 |