Kotlin Loops
Repeating code execution efficiently
🔄 What are Loops?
Loops allow you to repeat code multiple times without writing it over and over. They're essential for processing collections, counting, and automating repetitive tasks in your programs efficiently and elegantly.
// Simple loop example
for (i in 1..3) {
println("Count: $i")
}
Types of Loops
For Loop
Iterate over ranges and collections
for (i in 1..5) {
println(i)
}
While Loop
Repeat while condition is true
var count = 0
while (count < 3) {
println(count++)
}
Do-While Loop
Execute at least once, then check condition
var x = 0
do {
println("x = $x")
x++
} while (x < 2)
Collection Loops
Iterate through lists and arrays
val fruits = listOf("apple", "banana")
for (fruit in fruits) {
println(fruit)
}
🔹 For Loop Basics
The most common loop for iterating over ranges:
fun main() {
// Count from 1 to 5
println("Counting up:")
for (i in 1..5) {
println("Number: $i")
}
// Count backwards
println("\nCountdown:")
for (i in 5 downTo 1) {
println("$i...")
}
println("Blast off! 🚀")
}
Output:
Counting up:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Countdown:
5...
4...
3...
2...
1...
Blast off! 🚀
🔹 While Loop
Repeat code while a condition remains true:
fun main() {
var password = ""
var attempts = 0
while (password != "secret" && attempts < 3) {
attempts++
println("Attempt $attempts: Enter password")
// Simulating user input
password = when (attempts) {
1 -> "wrong"
2 -> "incorrect"
3 -> "secret"
else -> ""
}
if (password == "secret") {
println("Access granted! ✅")
} else {
println("Wrong password! ❌")
}
}
}
Output:
Attempt 1: Enter password
Wrong password! ❌
Attempt 2: Enter password
Wrong password! ❌
Attempt 3: Enter password
Access granted! ✅
🔹 Do-While Loop
Execute code at least once, then check condition:
fun main() {
var userChoice: String
do {
println("=== Menu ===")
println("1. Play Game")
println("2. View Scores")
println("3. Exit")
println("Choose an option:")
// Simulating user input
userChoice = "2" // User chooses option 2
when (userChoice) {
"1" -> println("Starting game... 🎮")
"2" -> println("High Score: 1000 points 🏆")
"3" -> println("Thanks for playing! 👋")
else -> println("Invalid choice!")
}
// For demo, we'll exit after one iteration
userChoice = "3"
} while (userChoice != "3")
}
Output:
=== Menu ===
1. Play Game
2. View Scores
3. Exit
Choose an option:
High Score: 1000 points 🏆
Thanks for playing! 👋
🔹 Looping Through Collections
Iterate over lists, arrays, and other collections:
fun main() {
val fruits = listOf("Apple", "Banana", "Orange", "Grape")
val numbers = arrayOf(10, 20, 30, 40, 50)
// Loop through list
println("Fruits in basket:")
for (fruit in fruits) {
println("🍎 $fruit")
}
// Loop with index
println("\nNumbers with positions:")
for ((index, number) in numbers.withIndex()) {
println("Position $index: $number")
}
// Loop through indices
println("\nUsing indices:")
for (i in fruits.indices) {
println("${i + 1}. ${fruits[i]}")
}
}
Output:
Fruits in basket:
🍎 Apple
🍎 Banana
🍎 Orange
🍎 Grape
Numbers with positions:
Position 0: 10
Position 1: 20
Position 2: 30
Position 3: 40
Position 4: 50
Using indices:
1. Apple
2. Banana
3. Orange
4. Grape