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