Kotlin While Loop
Introduction
Loops are fundamental programming constructs that allow us to execute a block of code repeatedly based on a condition. In Kotlin, the while
loop is one of the basic loop structures that continues to execute its body as long as its condition evaluates to true
.
Unlike for
loops (which typically iterate a fixed number of times), while
loops are particularly useful when you don't know in advance how many times you need to repeat a certain task.
Basic Syntax
The basic syntax of a while
loop in Kotlin is:
while (condition) {
// code to be executed repeatedly
// as long as condition is true
}
Here's how it works:
- The condition is evaluated
- If the condition is
true
, the code inside the loop executes - After execution, control returns to step 1
- If the condition is
false
, the loop terminates and execution continues with the code after the loop
Simple While Loop Example
Let's start with a basic example that counts from 1 to 5:
fun main() {
var counter = 1
while (counter <= 5) {
println("Count: $counter")
counter++ // increment counter by 1
}
println("Loop finished")
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finished
In this example:
- We initialize a
counter
variable to 1 - We run the loop as long as
counter
is less than or equal to 5 - Inside the loop, we print the current value and increment the counter
- Once the counter reaches 6, the condition becomes false, and the loop exits
The do-while Loop Variant
Kotlin also provides a do-while
loop, which is similar to the while
loop but guarantees that the code block will execute at least once, regardless of whether the condition is initially true
:
do {
// code to be executed at least once
// and then repeatedly as long as condition is true
} while (condition)
Example of do-while Loop
fun main() {
var number = 6
do {
println("Current number: $number")
number++
} while (number <= 5)
println("Loop finished with number = $number")
}
Output:
Current number: 6
Loop finished with number = 7
Notice that even though the condition number <= 5
was false from the beginning (since number
was initialized as 6), the loop body still executed once before checking the condition.
Infinite Loops
A loop whose condition always evaluates to true
is called an infinite loop. They can be intentional or accidental:
// Intentional infinite loop
while (true) {
println("This will run forever unless broken")
// usually contains a break statement somewhere
}
To exit an infinite loop, you can use the break
statement:
fun main() {
var counter = 1
while (true) {
println("Iteration: $counter")
counter++
if (counter > 5) {
println("Breaking the loop")
break
}
}
println("Loop finished")
}
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Breaking the loop
Loop finished
Using continue in While Loops
The continue
statement skips the current iteration of the loop and proceeds with the next iteration:
fun main() {
var counter = 0
while (counter < 10) {
counter++
// Skip printing even numbers
if (counter % 2 == 0) {
continue
}
println("Odd number: $counter")
}
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
Nested While Loops
You can nest one while loop inside another:
fun main() {
var i = 1
while (i <= 3) {
println("Outer loop: $i")
var j = 1
while (j <= 2) {
println(" Inner loop: $j")
j++
}
i++
}
}
Output:
Outer loop: 1
Inner loop: 1
Inner loop: 2
Outer loop: 2
Inner loop: 1
Inner loop: 2
Outer loop: 3
Inner loop: 1
Inner loop: 2
Practical Examples
Example 1: User Input Validation
The while
loop is great for validating user input until they provide a valid response:
fun main() {
var userInput: Int?
var validInput = false
println("Please enter a number between 1 and 10:")
while (!validInput) {
try {
userInput = readLine()?.toInt()
if (userInput != null && userInput in 1..10) {
println("Thank you! You entered: $userInput")
validInput = true
} else {
println("Invalid input. Please enter a number between 1 and 10:")
}
} catch (e: NumberFormatException) {
println("Invalid input. Please enter a number between 1 and 10:")
}
}
}
In this example, the loop continues until the user provides a valid number between 1 and 10.
Example 2: Menu-Driven Application
A while
loop can implement a menu-driven program structure:
fun main() {
var running = true
while (running) {
println("\nMenu:")
println("1. Say Hello")
println("2. Calculate Sum")
println("3. Exit")
print("Enter your choice: ")
when (readLine()?.toIntOrNull()) {
1 -> println("Hello, user!")
2 -> {
println("Enter two numbers:")
val a = readLine()?.toDoubleOrNull() ?: 0.0
val b = readLine()?.toDoubleOrNull() ?: 0.0
println("Sum: ${a + b}")
}
3 -> {
println("Exiting program...")
running = false
}
else -> println("Invalid option. Please try again.")
}
}
}
This example shows how a while loop can create an interactive menu that runs until the user chooses to exit.
Best Practices
-
Always ensure the loop condition will eventually become false: Make sure your loop has a way to terminate, otherwise it becomes an infinite loop.
-
Use appropriate loop variables: Make sure your loop variables are correctly initialized and updated within the loop.
-
Consider loop alternatives: In some cases, a
for
loop or other Kotlin constructs like.repeat()
or collection functions may be more appropriate. -
Be careful with loop conditions: Double-check that your loop condition is correct to avoid off-by-one errors.
-
Keep loops simple: If your loop body becomes complex, consider refactoring parts of it into functions.
Common Pitfalls
Infinite Loops
The most common mistake is creating an accidental infinite loop by forgetting to update the condition variable:
// Problematic code - infinite loop
var i = 1
while (i <= 5) {
println(i)
// forgot to increment i!
}
Fencepost Errors
Another common issue is "fencepost" or "off-by-one" errors:
var i = 0
while (i < 5) {
i++
println(i) // Prints 1 through 5, not 0 through 4
}
Be clear about whether you want to include or exclude the boundary values in your loop.
Summary
The while
loop in Kotlin is a fundamental control structure that allows you to repeatedly execute code based on a condition. Key points to remember:
- A
while
loop executes its body as long as its condition istrue
- A
do-while
loop always executes its body at least once - Use
break
to exit a loop early - Use
continue
to skip to the next iteration - Be cautious about infinite loops
- While loops are ideal when the number of iterations is not known in advance
Exercises
To solidify your understanding of Kotlin while loops, try these exercises:
-
Write a program that uses a while loop to find the sum of all numbers from 1 to n, where n is provided by the user.
-
Create a guessing game where the computer generates a random number between 1 and 100, and the user tries to guess it. Use a while loop to keep asking until they get it right.
-
Implement a simple calculator program that uses a do-while loop to allow the user to perform multiple calculations until they choose to exit.
-
Write a program that prints a countdown from 10 to 1, then prints "Blastoff!"
-
Create a program that uses a while loop to print the first 10 Fibonacci numbers.
Additional Resources
- Official Kotlin Documentation on Control Flow
- Kotlin Playground - Test your while loops online
- Kotlin Koans - Interactive exercises to learn Kotlin
Happy coding with Kotlin while loops!
If you spot any mistakes on this website, please let me know at feedback@compilenrun.com. I’d greatly appreciate your feedback! :)