0
0
Kotlinprogramming~15 mins

While and do-while loops in Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - While and do-while loops
What is it?
While and do-while loops are ways to repeat a block of code multiple times based on a condition. A while loop checks the condition before running the code, so it might not run at all if the condition is false. A do-while loop runs the code first, then checks the condition, so it always runs at least once. These loops help automate repetitive tasks in programs.
Why it matters
Without loops like while and do-while, programmers would have to write the same code again and again for repeated actions, which is slow and error-prone. Loops make programs efficient and easier to read by handling repetition automatically. They are essential for tasks like reading user input until it is valid or processing items until a goal is met.
Where it fits
Before learning loops, you should understand basic Kotlin syntax and how conditions work with if statements. After mastering while and do-while loops, you can learn for loops and more advanced control flow like break and continue statements.
Mental Model
Core Idea
A while loop repeats code as long as a condition is true, checking before each run, while a do-while loop runs the code first and then checks the condition to decide if it should repeat.
Think of it like...
Imagine a game where you keep rolling a dice until you get a six. With a while loop, you check if you rolled a six before rolling again, so you might never roll if you start with a six. With a do-while loop, you roll once first, then decide if you need to roll again.
┌───────────────┐       ┌───────────────┐
│   Start       │       │   Start       │
└──────┬────────┘       └──────┬────────┘
       │                         │
       ▼                         ▼
  ┌───────────┐             ┌───────────┐
  │ Check     │             │ Execute   │
  │ condition │             │ code once │
  └────┬──────┘             └────┬──────┘
       │                         │
   True│                         ▼
       ▼                  ┌───────────────┐
  ┌───────────┐           │ Check         │
  │ Execute   │           │ condition     │
  │ code      │           └────┬──────────┘
  └────┬──────┘                │
       │                       │True
       └───────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding basic while loop
🤔
Concept: Introduces the while loop structure and how it repeats code while a condition is true.
In Kotlin, a while loop looks like this: var count = 1 while (count <= 5) { println("Count is $count") count++ } This code prints numbers from 1 to 5. The condition 'count <= 5' is checked before each loop run. If true, the code inside runs; then count increases by 1.
Result
Output: Count is 1 Count is 2 Count is 3 Count is 4 Count is 5
Understanding that the condition is checked before running the loop body helps predict if the loop runs zero or more times.
2
FoundationIntroducing do-while loop basics
🤔
Concept: Shows how do-while loops run the code block first, then check the condition to decide on repeating.
A do-while loop in Kotlin looks like this: var count = 1 do { println("Count is $count") count++ } while (count <= 5) Here, the code inside 'do' runs once before the condition 'count <= 5' is checked. Then it repeats if true.
Result
Output: Count is 1 Count is 2 Count is 3 Count is 4 Count is 5
Knowing that do-while always runs the code at least once is key to choosing the right loop type.
3
IntermediateComparing while and do-while loops
🤔Before reading on: Do you think a while loop always runs at least once? Commit to yes or no.
Concept: Explains the difference in when the condition is checked and how it affects loop execution count.
Consider this example: var count = 10 while (count < 5) { println("Count is $count") count++ } var count2 = 10 do { println("Count2 is $count2") count2++ } while (count2 < 5) The while loop condition is false at start, so it never runs. The do-while loop runs once before checking and stops after.
Result
Output: Count2 is 10
Understanding this difference helps avoid bugs where code inside a loop might not run when expected.
4
IntermediateUsing loops for input validation
🤔Before reading on: Would a while or do-while loop be better to ask user input at least once? Commit to your answer.
Concept: Shows practical use of loops to repeat actions until a condition is met, like valid user input.
Example: var input: String? do { println("Enter a number between 1 and 10:") input = readLine() } while (input == null || input.toIntOrNull() !in 1..10) This loop asks the user for input at least once and repeats until the input is a number between 1 and 10.
Result
The program keeps asking until valid input is entered.
Knowing when to use do-while ensures user interaction happens at least once, improving user experience.
5
IntermediateControlling loops with break and continue
🤔Before reading on: Can you stop a loop early or skip just one iteration? Commit to yes or no.
Concept: Introduces break to exit loops early and continue to skip to the next iteration.
Example: var count = 1 while (count <= 10) { if (count == 5) break if (count % 2 == 0) { count++ continue } println("Count is $count") count++ } This prints odd numbers from 1 to 4 and stops when count reaches 5.
Result
Output: Count is 1 Count is 3
Knowing how to control loop flow precisely prevents infinite loops and allows flexible repetition.
6
AdvancedNested while and do-while loops
🤔Before reading on: Do you think loops can be placed inside other loops? Commit to yes or no.
Concept: Shows how loops can be nested to handle complex repeated tasks like grids or multiple conditions.
Example: var i = 1 while (i <= 3) { var j = 1 do { println("i=$i, j=$j") j++ } while (j <= 2) i++ } This prints pairs of i and j values, repeating inner loop fully for each outer loop step.
Result
Output: i=1, j=1 i=1, j=2 i=2, j=1 i=2, j=2 i=3, j=1 i=3, j=2
Understanding nested loops unlocks the ability to handle multi-dimensional data and complex repetition.
7
ExpertLoop performance and pitfalls in Kotlin
🤔Before reading on: Do you think while loops are always the fastest way to repeat code? Commit to yes or no.
Concept: Discusses performance considerations, common mistakes like infinite loops, and Kotlin-specific optimizations.
While loops can cause infinite loops if the condition never becomes false. Kotlin's for loops over ranges or collections are often clearer and optimized. Using while loops with mutable variables requires care to update conditions properly. Also, Kotlin supports inline functions and lambdas that sometimes replace loops for better readability and performance.
Result
Knowing these helps write safer and faster Kotlin code.
Understanding loop internals and Kotlin idioms prevents bugs and improves code quality in real projects.
Under the Hood
At runtime, a while loop repeatedly checks a condition before executing its body. If the condition is true, the code inside runs, then the condition is checked again. This cycle continues until the condition becomes false. A do-while loop differs by running the code body first, then checking the condition after each execution. Internally, this is implemented as a jump back to the condition check or loop start in the compiled bytecode.
Why designed this way?
The while loop was designed to allow zero or more repetitions, useful when the loop might not run at all. The do-while loop was added to cover cases where the code must run at least once, such as prompting user input. This separation gives programmers clear control over loop behavior and prevents awkward workarounds.
┌───────────────┐
│   Start       │
└──────┬────────┘
       │
       ▼
  ┌───────────┐
  │ Check     │
  │ condition │
  └────┬──────┘
       │True
       ▼
  ┌───────────┐
  │ Execute   │
  │ loop body │
  └────┬──────┘
       │
       └─────┐
             ▼
       (repeat check)


Do-while loop:

┌───────────────┐
│   Start       │
└──────┬────────┘
       │
       ▼
  ┌───────────┐
  │ Execute   │
  │ loop body │
  └────┬──────┘
       │
       ▼
  ┌───────────┐
  │ Check     │
  │ condition │
  └────┬──────┘
       │True
       └─────┐
             ▼
       (repeat execution)
Myth Busters - 4 Common Misconceptions
Quick: Does a while loop always run its code at least once? Commit to yes or no.
Common Belief:A while loop always runs the code inside at least once.
Tap to reveal reality
Reality:A while loop checks the condition before running the code, so if the condition is false initially, the code inside never runs.
Why it matters:Assuming the code runs at least once can cause bugs where initialization or user input is skipped unexpectedly.
Quick: Can a do-while loop run zero times? Commit to yes or no.
Common Belief:A do-while loop might not run if the condition is false at the start.
Tap to reveal reality
Reality:A do-while loop always runs the code block once before checking the condition, so it runs at least once no matter what.
Why it matters:Misunderstanding this can lead to incorrect assumptions about program flow, especially in input validation.
Quick: Is it safe to forget updating the loop variable inside a while loop? Commit to yes or no.
Common Belief:You can write a while loop without changing the condition variables inside the loop body.
Tap to reveal reality
Reality:If the condition variables are not updated, the loop can become infinite, causing the program to freeze or crash.
Why it matters:This is a common source of bugs and crashes in programs using loops.
Quick: Are while loops always the best choice for repeating code? Commit to yes or no.
Common Belief:While loops are always the best and fastest way to repeat code in Kotlin.
Tap to reveal reality
Reality:For many cases, Kotlin's for loops or functional constructs like sequences and lambdas are clearer and more efficient.
Why it matters:Relying only on while loops can lead to less readable and less optimized code.
Expert Zone
1
While loops can be combined with Kotlin's smart casting to reduce explicit type checks inside the loop.
2
Do-while loops are rarely used in Kotlin compared to while and for loops, but they shine in scenarios requiring guaranteed single execution like menu prompts.
3
Kotlin's inline functions and lambdas can sometimes replace loops for better performance and readability, especially in collection processing.
When NOT to use
Avoid while and do-while loops when iterating over collections or ranges; prefer Kotlin's for loops or functional methods like map, filter, and forEach for clearer and safer code.
Production Patterns
In production Kotlin code, while loops are often used for waiting on conditions like network responses or user input, with careful timeout handling. Do-while loops appear in user interface code to ensure at least one prompt. Nested loops handle multi-dimensional data like grids or matrices, but are often replaced by higher-order functions for clarity.
Connections
Recursion
Alternative pattern for repetition
Understanding loops helps grasp recursion, as both repeat actions but recursion uses function calls instead of explicit loops.
Finite State Machines
Loops model repeated state checks
While loops mimic state machines by repeatedly checking conditions and transitioning states, linking programming to system design.
Human habit formation
Repetition based on conditions
Loops in programming are like habits in life: actions repeated until a goal or condition changes, showing how computers and humans both rely on repetition.
Common Pitfalls
#1Infinite loop due to missing condition update
Wrong approach:var count = 1 while (count <= 5) { println("Count is $count") // missing count++ here }
Correct approach:var count = 1 while (count <= 5) { println("Count is $count") count++ }
Root cause:Forgetting to update the loop variable means the condition never changes, causing endless repetition.
#2Using while loop when code must run at least once
Wrong approach:var input: String? = null while (input != "yes") { println("Type 'yes' to continue") input = readLine() }
Correct approach:var input: String? do { println("Type 'yes' to continue") input = readLine() } while (input != "yes")
Root cause:Using while loop checks condition before first run, so if input starts as 'yes', code never runs; do-while ensures one run.
#3Misusing break and continue causing unexpected flow
Wrong approach:var i = 0 while (i < 5) { if (i == 2) continue println(i) i++ }
Correct approach:var i = 0 while (i < 5) { if (i == 2) { i++ continue } println(i) i++ }
Root cause:Using continue without updating loop variables can cause infinite loops by skipping the increment step.
Key Takeaways
While loops check the condition before running the code, so they may run zero or more times.
Do-while loops run the code first, then check the condition, guaranteeing at least one execution.
Choosing between while and do-while depends on whether you need the code to run at least once.
Always update loop variables inside the loop to avoid infinite loops.
In Kotlin, for loops and functional methods often provide clearer and safer alternatives to while loops.