Kotlin Control Flow Statements
Estimated reading: 3 minutes 42 views

🔄 Kotlin – While Loop: Repeating Logic Until a Condition Fails

🧲 Introduction – Why Learn Kotlin While Loops?

The while loop in Kotlin is used when you need to execute a block of code repeatedly based on a dynamic condition. Unlike the for loop (used with ranges or collections), while is ideal when you don’t know the exact number of iterations in advance—such as reading input or waiting for an event.

🎯 In this guide, you’ll learn:

  • The syntax and structure of while and do-while loops
  • Real-world use cases for both loop types
  • Differences between while and for
  • Best practices and common mistakes

🔁 Basic While Loop Syntax

var i = 1

while (i <= 5) {
    println("i = $i")
    i++
}

🟢 Output:

i = 1  
i = 2  
i = 3  
i = 4  
i = 5
  • Executes the block as long as the condition is true.
  • The condition is checked before each iteration.

🔂 Kotlin Do…While Loop

Use do…while when you want the block to run at least once, even if the condition is false.

var j = 1

do {
    println("j = $j")
    j++
} while (j <= 3)

🟢 Output:

j = 1  
j = 2  
j = 3
  • Checks the condition after running the block.

⚖️ While vs Do…While

Featurewhiledo…while
Condition checkBefore loop startsAfter loop runs once
Guaranteed executionNo (may not run)Yes (runs at least once)
Use caseWhen unsure if loop should runWhen block must run at least once

🧪 Practical Example – User Input (Simulated)

var input: String?

do {
    println("Enter something (type 'exit' to quit):")
    input = readLine()
} while (input != "exit")

🧠 This is a real-world use case of do…while, as the prompt should show at least once.


🔁 Infinite Loop with Break Condition

var x = 1

while (true) {
    println("x = $x")
    if (x == 3) break
    x++
}

✅ Use break to exit the loop manually when a condition is met.


⛔ Common Mistakes in While Loops

❌ Mistake✅ Solution
Forgetting to update conditionEnsure loop variable changes inside loop
Infinite loop unintentionallyUse break conditions or counter checks
Off-by-one errorsDouble-check conditions (<= vs <)
Skipping do in do-whileRemember, it’s do { ... } while (cond)

✅ Best Practices for While Loops

PracticeReason
Use while when condition is dynamicGives better control and clarity
Add break conditions for safetyPrevents infinite loops
Use comments for complex loop logicImproves readability and maintainability
Use do-while when guaranteed first executionReduces redundant checks

📌 Summary – Recap & Next Steps

Kotlin’s while and do-while loops are ideal for dynamic looping scenarios where the iteration count isn’t predetermined. They offer flexible control flow for input processing, polling systems, retry logic, and more.

🔍 Key Takeaways:

  • Use while for conditional pre-check loops.
  • Use do-while when at least one execution is needed.
  • Break infinite loops safely using break.
  • Always ensure your condition changes within the loop.

⚙️ Practical Use:
While loops are often used in user interaction, file reading, data polling, or game loops—anywhere continuous checking is required.


❓ FAQs – Kotlin While Loops

What’s the difference between while and do…while in Kotlin?
while checks the condition before the first iteration; do…while runs the loop once before checking the condition.


Can I write an infinite while loop in Kotlin?
✅ Yes. Use while (true) and break manually:

while (true) {
    if (someCondition) break
}

Is do…while mandatory for repeated input prompts?
✅ Not mandatory, but preferred when you want the prompt to show at least once.


Can I use continue inside a while loop?
✅ Yes. It skips the current iteration and moves to the next condition check:

while (i < 10) {
    i++
    if (i % 2 == 0) continue
    println(i)
}

Can Kotlin while loops return values?
✅ No. Unlike expressions like if or when, while is a statement, not an expression—it doesn’t return a value.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Kotlin – While Loop

Or Copy Link

CONTENTS
Scroll to Top