Kotlin Loops: The Magic of Repetition 🔄🚀
Imagine you're a robot 🤖 assigned to wash 10 dishes 🍽️. Would you manually wash each dish one by one, or would you automate the process?
Loops in Kotlin help us automate repetitive tasks so that we don’t have to write the same code again and again.
📌 In this blog, we’ll cover:
✅ What are loops? 🤔
✅ Types of loops in Kotlin (for, while, do-while) 🔁
✅ Features, examples, and best use cases ✨
Let’s dive into loops! 🏊♂️
1️⃣ What Are Loops? 🔄
A loop is a control structure that repeats a block of code until a condition is met.
📌 Think of it like this:
- "Keep running until you reach the finish line." 🏃♂️🏁
- "Keep watering the plant until the soil is moist." 🌱💦
Loops help in:
🔹 Reducing redundancy (no need to copy-paste code).
🔹 Automating tasks (like processing lists, arrays, etc.).
🔹 Making the code clean and efficient.
2️⃣ Types of Loops in Kotlin 🏗️
Kotlin provides three types of loops:
Loop Type | When to Use? |
---|---|
for loop |
When iterating over a range, list, or array. |
while loop |
When we don’t know how many times the loop should run. |
do-while loop |
When we want to execute at least once, then check the condition. |
Let’s explore each of them in detail! 🕵️♂️
3️⃣ for
Loop: The Repeater 🔁
The for
loop is used when we need to iterate over a range, list, or array.
🔹 Syntax of for
loop
for (item in collection) {
// Execute this block
}
🔹 Example: Counting from 1 to 5
for (i in 1..5) {
println("Number: $i")
}
📌 Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
🧐 Explanation:
1..5
is a range (numbers from 1 to 5).- The loop runs 5 times, printing each number.
4️⃣ for
with step
& downTo
🚀
🔹 Example: Skipping Numbers with step
for (i in 1..10 step 2) {
println(i)
}
📌 Output: 1 3 5 7 9
🔹 Example: Counting Backward with downTo
for (i in 10 downTo 1) {
println(i)
}
📌 Output: 10 9 8 7 6 5 4 3 2 1
5️⃣ while
Loop: The Condition Checker 🔄
A while
loop repeats as long as a condition is true
.
🔹 Syntax of while
loop
while (condition) {
// Execute this block
}
🔹 Example: Counting Down to Launch 🚀
var countdown = 5
while (countdown > 0) {
println("Launching in $countdown...")
countdown-- // Decrease countdown
}
println("🚀 Blast Off!")
📌 Output:
Launching in 5...
Launching in 4...
Launching in 3...
Launching in 2...
Launching in 1...
🚀 Blast Off!
🧐 Explanation:
- The loop runs until
countdown
reaches 0. countdown--
decreases the value in each iteration.
6️⃣ do-while
Loop: The Must-Run Loop ✅
Unlike while
, the do-while
loop always runs at least once (because the condition is checked after execution).
🔹 Syntax of do-while
loop
do {
// Execute this block
} while (condition)
🔹 Example: Asking for Password 🔑
var password: String
do {
print("Enter password: ")
password = readLine()!!
} while (password != "kotlin123")
println("✅ Access Granted!")
📌 How It Works?
- The loop always asks for a password at least once.
- If the user enters the wrong password, it repeats.
- If they enter
"kotlin123"
, it exits the loop.
7️⃣ Breaking & Skipping Loops 🚀
🔹 break
: Stops the Loop Immediately 🚫
for (i in 1..10) {
if (i == 5) break // Stops loop when i is 5
println(i)
}
📌 Output: 1 2 3 4
🔹 continue
: Skips Current Iteration 🔄
for (i in 1..5) {
if (i == 3) continue // Skips 3
println(i)
}
📌 Output: 1 2 4 5
(Skips 3
)
8️⃣ Infinite Loops: BE CAREFUL! ⚠️
If a loop never meets the exit condition, it becomes infinite!
❌ Example: Infinite while
Loop
var x = 5
while (x > 0) {
println("Looping forever...") // Oops! No x--
}
🔴 Solution: Always update the loop variable (x--
in this case).
9️⃣ for
vs while
vs do-while
: When to Use What? 🤔
Feature | for Loop |
while Loop |
do-while Loop |
---|---|---|---|
Use Case | Known number of repetitions | Unknown repetitions | Must execute at least once |
Condition Checking | Before loop starts | Before each iteration | After first execution |
Example | Iterating over lists, ranges | Waiting for user input | Login system (password check) |
🔟 Conclusion: Loops Make Life Easier! 🚀
🔹 Use for
for ranges, lists, and arrays.
🔹 Use while
when the number of repetitions is unknown.
🔹 Use do-while
when you need to run at least once.
🔹 Use break
and continue
to control loops efficiently.
Now, go ahead and experiment with Kotlin loops in your own projects! 🎯
💬 Which loop do you use the most? Let me know in the comments! ⬇️😊