Kotlin Do...While Loop

Execute first, then check condition

šŸŽÆ What is Do...While Loop?

Do...While loop executes code at least once before checking the condition. It's perfect for menus, user input validation, and situations where you need to run code first, then decide whether to continue repeating.


// Basic do-while loop
var count = 1
do {
    println("Count: $count")
    count++
} while (count <= 3)
                                    

Do...While Features

ā–¶ļø

Execute First

Always runs at least once

do {
    println("This runs once")
} while (false)
šŸ”

Check After

Condition checked after execution

do {
    // Code here
    x++
} while (x < 10)
šŸ½ļø

Perfect for Menus

Show menu at least once

do {
    showMenu()
    choice = getInput()
} while (choice != "exit")
āœ…

Input Validation

Ask for input until valid

do {
    print("Enter age: ")
    age = readLine()?.toIntOrNull()
} while (age == null)

šŸ”¹ Basic Do...While Loop

Simple counting example:

fun main() {
    // Count from 1 to 5
    var number = 1
    
    println("Counting with do-while:")
    do {
        println("Number: $number")
        number++
    } while (number <= 5)
    
    // This runs even when condition is false
    var x = 10
    println("\nThis runs even when x = 10:")
    do {
        println("x is $x (condition x < 5 is false)")
        x++
    } while (x < 5)
    
    println("Loop finished!")
}

Output:

Counting with do-while:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5


This runs even when x = 10:

x is 10 (condition x < 5 is false)

Loop finished!

šŸ”¹ Menu System

Perfect use case for do-while loop:

fun main() {
    var choice: String
    var gameScore = 0
    
    do {
        println("\nšŸŽ® === GAME MENU ===")
        println("1. Play Game")
        println("2. View High Score")
        println("3. Reset Score")
        println("4. Exit")
        println("Current Score: $gameScore")
        print("Choose option (1-4): ")
        
        // Simulating user input
        choice = when ((1..4).random()) {
            1 -> {
                println("1")
                gameScore += (10..50).random()
                println("šŸŽÆ Game played! Earned ${gameScore - (gameScore - (10..50).random())} points!")
                "1"
            }
            2 -> {
                println("2")
                println("šŸ† High Score: $gameScore")
                "2"
            }
            3 -> {
                println("3")
                gameScore = 0
                println("šŸ”„ Score reset!")
                "3"
            }
            else -> {
                println("4")
                println("šŸ‘‹ Thanks for playing!")
                "4"
            }
        }
        
        if (choice != "4") {
            println("Press any key to continue...")
        }
        
    } while (choice != "4")
}

Output:

šŸŽ® === GAME MENU ===

1. Play Game

2. View High Score

3. Reset Score

4. Exit

Current Score: 0

Choose option (1-4): 1

šŸŽÆ Game played! Earned 25 points!

Press any key to continue...


šŸŽ® === GAME MENU ===

1. Play Game

2. View High Score

3. Reset Score

4. Exit

Current Score: 25

Choose option (1-4): 4

šŸ‘‹ Thanks for playing!

šŸ”¹ Input Validation

Keep asking until valid input:

fun main() {
    var age: Int?
    var name: String
    var email: String
    
    // Validate age
    do {
        print("Enter your age (18-100): ")
        // Simulating user input
        val ageInput = listOf("15", "abc", "25", "150").random()
        println(ageInput)
        
        age = ageInput.toIntOrNull()
        
        when {
            age == null -> println("āŒ Please enter a valid number!")
            age < 18 -> println("āŒ You must be at least 18 years old!")
            age > 100 -> println("āŒ Please enter a realistic age!")
            else -> println("āœ… Age accepted!")
        }
    } while (age == null || age < 18 || age > 100)
    
    // Validate name
    do {
        print("Enter your name (at least 2 characters): ")
        // Simulating user input
        name = listOf("A", "", "John", "X").random()
        println(name)
        
        if (name.length < 2) {
            println("āŒ Name must be at least 2 characters long!")
        } else {
            println("āœ… Name accepted!")
        }
    } while (name.length < 2)
    
    println("\nšŸŽ‰ Registration complete!")
    println("Name: $name")
    println("Age: $age")
}

Output:

Enter your age (18-100): 15

āŒ You must be at least 18 years old!

Enter your age (18-100): abc

āŒ Please enter a valid number!

Enter your age (18-100): 25

āœ… Age accepted!

Enter your name (at least 2 characters): A

āŒ Name must be at least 2 characters long!

Enter your name (at least 2 characters): John

āœ… Name accepted!


šŸŽ‰ Registration complete!

Name: John

Age: 25

šŸ”¹ Game Loop Example

Simple guessing game:

fun main() {
    val secretNumber = (1..10).random()
    var guess: Int?
    var attempts = 0
    var playAgain: String
    
    do {
        println("\nšŸŽ² === NUMBER GUESSING GAME ===")
        println("I'm thinking of a number between 1 and 10!")
        attempts = 0
        
        do {
            attempts++
            print("Attempt $attempts - Enter your guess: ")
            
            // Simulating user guesses
            val guessInput = (1..10).random().toString()
            println(guessInput)
            guess = guessInput.toIntOrNull()
            
            when {
                guess == null -> println("āŒ Please enter a valid number!")
                guess < secretNumber -> println("šŸ“ˆ Too low! Try higher!")
                guess > secretNumber -> println("šŸ“‰ Too high! Try lower!")
                else -> {
                    println("šŸŽ‰ Correct! You guessed it in $attempts attempts!")
                    break
                }
            }
        } while (guess != secretNumber)
        
        print("\nPlay again? (y/n): ")
        playAgain = listOf("y", "n").random()
        println(playAgain)
        
    } while (playAgain.lowercase() == "y")
    
    println("Thanks for playing! šŸ‘‹")
}

Output:

šŸŽ² === NUMBER GUESSING GAME ===

I'm thinking of a number between 1 and 10!

Attempt 1 - Enter your guess: 5

šŸ“ˆ Too low! Try higher!

Attempt 2 - Enter your guess: 8

šŸ“‰ Too high! Try lower!

Attempt 3 - Enter your guess: 7

šŸŽ‰ Correct! You guessed it in 3 attempts!


Play again? (y/n): n

Thanks for playing! šŸ‘‹

šŸ”¹ Do...While vs While

Key differences between the two loops:

šŸ”„ While Loop:

var x = 10
while (x < 5) {
    println("This never prints")
    x++
}
// Output: (nothing)

šŸŽÆ Do...While Loop:

var x = 10
do {
    println("This prints once: $x")
    x++
} while (x < 5)
// Output: This prints once: 10

šŸ“‹ When to use each:

  • While: When you might not need to execute at all
  • Do-While: When you need to execute at least once
  • Do-While: Perfect for menus and input validation
  • While: Better for processing collections or counting

🧠 Test Your Knowledge

How many times will this code print "Hello"?
var i = 5; do { println("Hello"); i++ } while (i < 3)