Kotlin While Loop
Repeating code based on conditions
ā³ What is While Loop?
While loop repeats code as long as a condition remains true. It's perfect for situations where you don't know exactly how many times to repeat, like user input validation or processing data until completion.
// Basic while loop
var count = 1
while (count <= 3) {
println("Count: $count")
count++
}
While Loop Features
Condition Check
Checks condition before each iteration
while (x < 10) {
println(x)
x++
}
Unknown Iterations
Perfect when you don't know loop count
while (userInput != "quit") {
// Process input
userInput = readLine()
}
May Not Execute
Can skip entirely if condition is false
var x = 10
while (x < 5) {
// This never runs
println(x)
}
Variable Control
Loop variable must be updated inside
var i = 0
while (i < 5) {
println(i)
i++ // Important!
}
š¹ Basic While Loop
Simple counting with while loop:
fun main() {
// Count from 1 to 5
var number = 1
println("Counting with while loop:")
while (number <= 5) {
println("Number: $number")
number++ // Don't forget to increment!
}
println("Loop finished!")
}
Output:
Counting with while loop:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Loop finished!
š¹ User Input Simulation
Keep asking until correct input:
fun main() {
var password = ""
var attempts = 0
val correctPassword = "kotlin123"
while (password != correctPassword && attempts < 3) {
attempts++
println("Attempt $attempts: Enter password")
// Simulating different user inputs
password = when (attempts) {
1 -> "wrong"
2 -> "incorrect"
3 -> "kotlin123"
else -> ""
}
println("You entered: $password")
if (password == correctPassword) {
println("ā
Access granted!")
} else if (attempts < 3) {
println("ā Wrong password, try again!")
}
}
if (password != correctPassword) {
println("š Account locked after 3 failed attempts!")
}
}
Output:
Attempt 1: Enter password
You entered: wrong
ā Wrong password, try again!
Attempt 2: Enter password
You entered: incorrect
ā Wrong password, try again!
Attempt 3: Enter password
You entered: kotlin123
ā Access granted!
š¹ Processing Collections
Use while loop with collections:
fun main() {
val tasks = mutableListOf("Email", "Meeting", "Code Review", "Documentation")
println("š Task List:")
tasks.forEach { println("- $it") }
println("\nā³ Processing tasks...")
while (tasks.isNotEmpty()) {
val currentTask = tasks.removeAt(0) // Remove first task
println("ā
Completed: $currentTask")
println("š Remaining tasks: ${tasks.size}")
if (tasks.isNotEmpty()) {
println("š Next up: ${tasks[0]}")
println("---")
}
}
println("š All tasks completed!")
}
Output:
š Task List:
- Meeting
- Code Review
- Documentation
ā³ Processing tasks...
ā Completed: Email
š Remaining tasks: 3
š Next up: Meeting
---
ā Completed: Meeting
š Remaining tasks: 2
š Next up: Code Review
---
ā Completed: Code Review
š Remaining tasks: 1
š Next up: Documentation
---
ā Completed: Documentation
š Remaining tasks: 0
š All tasks completed!
š¹ Mathematical Calculations
Use while loop for calculations:
fun main() {
// Calculate factorial of 5
var number = 5
var factorial = 1
var temp = number
println("Calculating factorial of $number:")
while (temp > 0) {
println("$factorial Ć $temp = ${factorial * temp}")
factorial *= temp
temp--
}
println("Result: $number! = $factorial")
// Find first power of 2 greater than 100
var power = 1
var exponent = 0
println("\nFinding first power of 2 > 100:")
while (power <= 100) {
println("2^$exponent = $power")
exponent++
power *= 2
}
println("Answer: 2^$exponent = $power")
}
Output:
Calculating factorial of 5:
1 Ć 5 = 5
5 Ć 4 = 20
20 Ć 3 = 60
60 Ć 2 = 120
120 Ć 1 = 120
Result: 5! = 120
Finding first power of 2 > 100:
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
2^6 = 64
Answer: 2^7 = 128
š¹ Common Pitfalls
Avoid infinite loops and other issues:
ā ļø Infinite Loop Warning:
// DON'T DO THIS - Infinite loop!
var x = 1
while (x < 10) {
println(x)
// Forgot to increment x!
}
// CORRECT VERSION:
var x = 1
while (x < 10) {
println(x)
x++ // Always update the condition variable!
}
ā Best Practices:
- Always update the loop variable inside the loop
- Make sure the condition can eventually become false
- Consider using a counter to prevent infinite loops
- Test your loop with different starting values