Kotlin Do While Loop
Introduction
In programming, we often need to execute a block of code multiple times. Loops are control flow structures designed specifically for this purpose. The do-while loop is a variant of the while loop in Kotlin that guarantees the execution of a code block at least once before checking the condition for subsequent iterations.
Unlike a standard while loop that evaluates the condition before entering the loop, a do-while loop evaluates the condition after executing the loop body for the first time. This key difference makes do-while loops particularly useful when you need to ensure that a block of code runs at least once, regardless of the condition.
Basic Syntax
Here's the basic syntax of a do-while loop in Kotlin:
do {
// Code to be executed
} while (condition)
The loop works as follows:
- The code inside the
do
block executes first - Then the
condition
is evaluated - If the
condition
istrue
, the loop continues and the code inside thedo
block executes again - If the
condition
isfalse
, the loop terminates
Simple Do-While Loop Example
Let's start with a basic example that prints numbers from 1 to 5:
fun main() {
var i = 1
do {
println("Number: $i")
i++
} while (i <= 5)
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
In this example:
- We initialize a variable
i
with the value 1 - Inside the do-while loop, we print the current value of
i
and then increment it - The loop continues as long as
i
is less than or equal to 5
Do-While vs. While Loop
To understand the unique characteristic of do-while loops, let's compare it with a regular while loop:
fun main() {
println("Using while loop:")
var i = 6
while (i <= 5) {
println("Number: $i")
i++
}
println("\nUsing do-while loop:")
i = 6
do {
println("Number: $i")
i++
} while (i <= 5)
}
Output:
Using while loop:
Using do-while loop:
Number: 6
Notice the difference:
- The while loop body doesn't execute at all because the condition is false from the start
- The do-while loop executes once before checking the condition, so it prints "Number: 6"
Practical Examples
Example 1: Input Validation
One common real-world use case for do-while loops is input validation, where you want to ensure that the user provides valid input:
fun main() {
var userInput: Int
do {
print("Please enter a positive number: ")
userInput = readLine()?.toIntOrNull() ?: -1
if (userInput <= 0) {
println("That's not a positive number. Try again.")
}
} while (userInput <= 0)
println("Thank you! You entered: $userInput")
}
In this example:
- We keep asking the user for input until they provide a positive number
- The loop guarantees that we ask for input at least once
- We only exit the loop when valid input is provided
Example 2: Menu-Driven Program
Another practical application is creating menu-driven console applications:
fun main() {
var choice: Int
do {
println("\n--- Calculator Menu ---")
println("1. Add two numbers")
println("2. Subtract two numbers")
println("3. Multiply two numbers")
println("4. Divide two numbers")
println("5. Exit")
print("Enter your choice (1-5): ")
choice = readLine()?.toIntOrNull() ?: 0
when (choice) {
1 -> performAddition()
2 -> performSubtraction()
3 -> performMultiplication()
4 -> performDivision()
5 -> println("Exiting calculator...")
else -> println("Invalid choice. Please try again.")
}
} while (choice != 5)
}
fun performAddition() {
print("Enter first number: ")
val num1 = readLine()?.toDoubleOrNull() ?: 0.0
print("Enter second number: ")
val num2 = readLine()?.toDoubleOrNull() ?: 0.0
println("Result: ${num1 + num2}")
}
// Similar functions for other operations
fun performSubtraction() {
// Implementation omitted for brevity
println("Subtraction selected")
}
fun performMultiplication() {
// Implementation omitted for brevity
println("Multiplication selected")
}
fun performDivision() {
// Implementation omitted for brevity
println("Division selected")
}
This example demonstrates a menu-driven calculator where:
- The menu is displayed at least once
- The program continues to show the menu until the user chooses to exit
- The do-while loop creates a continuous interaction cycle
Example 3: Retry Mechanism
Do-while loops are excellent for implementing retry mechanisms:
fun main() {
val maxAttempts = 3
var currentAttempt = 0
var success = false
do {
currentAttempt++
println("Attempt $currentAttempt of $maxAttempts")
// Simulate an operation that might fail
val randomValue = (1..10).random()
success = randomValue > 7
if (success) {
println("Operation succeeded!")
} else {
println("Operation failed. Random value was: $randomValue (needed > 7)")
if (currentAttempt < maxAttempts) {
println("Retrying...")
} else {
println("Maximum attempts reached. Giving up.")
}
}
} while (!success && currentAttempt < maxAttempts)
}
This example shows how to implement a retry mechanism that:
- Makes at least one attempt
- Continues trying until either success is achieved or maximum attempts are reached
Common Pitfalls and Tips
1. Infinite Loops
Be careful not to create infinite loops:
// Potential infinite loop if you forget to increment i
do {
println("This might run forever!")
// Missing: i++
} while (i < 10)
Always ensure your loop has a way to terminate.
2. Loop Variables
It's a good practice to initialize loop control variables before the loop:
var counter = 1 // Good: Initialize before the loop
do {
println("Counter: $counter")
counter++
} while (counter <= 5)
3. Loop Condition Evaluation
Remember that in a do-while loop, the condition is evaluated after the loop body executes:
var x = 10
do {
println("Value of x: $x")
x -= 5
} while (x > 0)
Output:
Value of x: 10
Value of x: 5
Value of x: 0
Note that even though the condition checks for x > 0
, we still see "Value of x: 0" in the output because the condition is checked after the loop body runs.
Summary
The do-while loop in Kotlin is a powerful control flow structure that guarantees at least one execution of a code block before checking the condition for subsequent iterations. This makes it particularly useful for:
- Input validation where you need to prompt at least once
- Menu-driven programs that should display at least once
- Retry mechanisms where you want to make at least one attempt
- Any scenario where you need to guarantee that a block of code runs at least once
Key points to remember:
- The loop body always executes at least once
- The condition is checked after each execution of the loop body
- If the condition is true, the loop continues; otherwise, it terminates
- Be careful to avoid infinite loops by ensuring the loop condition can eventually become false
Exercises for Practice
- Write a program that uses a do-while loop to sum numbers entered by the user until they enter 0.
- Create a simple guessing game where the program generates a random number and the user has to guess it. Use a do-while loop to keep prompting the user until they guess correctly.
- Implement a password validation system that requires users to enter a password that meets certain criteria (e.g., minimum length, contains a digit, etc.). Use a do-while loop to keep asking until a valid password is provided.
- Create a simple ATM interface using a do-while loop that presents options to the user until they choose to exit.
Additional Resources
- Kotlin Official Documentation on Control Flow
- Kotlin Playground - Practice your do-while loops online
- Programming in Kotlin by Venkat Subramaniam - A comprehensive book on Kotlin programming
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)