
A Kotlin while loop is a control structure that repeatedly executes a block of code as long as a specified condition evaluates to true. Unlike other loop types, the while loop checks the condition before executing the loop body, making it perfect for scenarios where you need conditional repetition with pre-validation.
The while loop Kotlin syntax follows this basic structure:
while (condition) {
// Code block to execute
}
The loop continues executing until the condition becomes false, at which point the program control moves to the statement following the loop.
The Kotlin while loop syntax is straightforward and intuitive. Here’s the fundamental structure:
while (testExpression) {
// Loop body
// Code to execute repeatedly
}
trueLet’s examine a simple example that demonstrates basic while loop syntax Kotlin:
fun main() {
var counter = 1
while (counter <= 5) {
println("Count: $counter")
counter++
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
The Kotlin while loop evaluates the condition before executing the loop body. This means if the condition is initially false, the loop body never executes.
fun demonstratePreCondition() {
var number = 10
while (number < 5) {
println("This will never print")
number++
}
println("Loop finished without executing")
}
Variables declared inside the while loop Kotlin structure have local scope and are not accessible outside the loop.
fun scopeExample() {
var i = 0
while (i < 3) {
val loopVariable = "Local to loop"
println("$loopVariable - Iteration $i")
i++
}
// loopVariable is not accessible here
}
Without proper loop control, Kotlin while loops can become infinite. Always ensure the loop condition can eventually become false.
// Avoid this - infinite loop
fun infiniteLoopExample() {
var value = 1
while (value > 0) {
println("This runs forever")
value++ // This makes condition always true
}
}
Kotlin while loops support break and continue statements for enhanced control flow.
fun controlFlowExample() {
var num = 1
while (num <= 10) {
if (num == 5) {
num++
continue // Skip printing 5
}
if (num == 8) {
break // Exit loop when num reaches 8
}
println("Number: $num")
num++
}
}
Kotlin while loops are excellent for processing collections when you need index-based access:
fun processStringCollection() {
val fruits = listOf("apple", "banana", "orange", "grape")
var index = 0
while (index < fruits.size) {
println("Fruit ${index + 1}: ${fruits[index]}")
index++
}
}
While loops are perfect for input validation scenarios:
fun validateUserInput() {
print("Enter a positive number: ")
var input = readLine()?.toIntOrNull() ?: -1
while (input == null || input <= 0) {
print("Invalid input. Please enter a positive number: ")
input = readLine()?.toIntOrNull() ?: -1
}
println("You entered: $input")
}
Implementing mathematical algorithms with while loops in Kotlin:
fun calculateFactorial(n: Int): Long {
var result = 1L
var counter = 1
while (counter <= n) {
result *= counter
counter++
}
return result
}
While the standard Kotlin while loop checks the condition before execution, the do-while loop executes the body at least once:
do {
// Code block
} while (condition)
fun compareWhileLoops() {
// Standard while loop
var count1 = 10
while (count1 < 5) {
println("While: $count1") // Never executes
count1++
}
// Do-while loop
var count2 = 10
do {
println("Do-while: $count2") // Executes once
count2++
} while (count2 < 5)
}
fun counterPattern() {
var i = 0
while (i < 10) {
println("Counter: $i")
i += 2 // Increment by 2
}
}
fun processUntilCondition() {
val numbers = mutableListOf(1, 3, 5, 8, 12, 15)
var index = 0
while (index < numbers.size && numbers[index] % 2 != 0) {
println("Odd number: ${numbers[index]}")
index++
}
}
fun processFileLines(lines: List<String>) {
var lineIndex = 0
while (lineIndex < lines.size) {
val line = lines[lineIndex]
if (line.isBlank()) {
lineIndex++
continue
}
println("Processing: $line")
lineIndex++
}
}
import kotlin.random.Random
fun numberGuessingGame() {
val targetNumber = Random.nextInt(1, 101)
var attempts = 0
var hasWon = false
println("Welcome to the Number Guessing Game!")
println("I'm thinking of a number between 1 and 100.")
while (!hasWon && attempts < 5) {
print("Enter your guess: ")
val guess = readLine()?.toIntOrNull()
if (guess == null) {
println("Please enter a valid number.")
continue
}
attempts++
when {
guess == targetNumber -> {
hasWon = true
println("Congratulations! You guessed it in $attempts attempts!")
}
guess < targetNumber -> println("Too low! Try again.")
else -> println("Too high! Try again.")
}
}
if (!hasWon) {
println("Game over! The number was $targetNumber")
}
}
fun main() {
numberGuessingGame()
}
data class BankAccount(var balance: Double, val accountNumber: String)
fun bankingSimulation() {
val account = BankAccount(1000.0, "ACC-12345")
var continueTransactions = true
println("Welcome to Kotlin Bank!")
println("Account: ${account.accountNumber}")
println("Current Balance: $${account.balance}")
while (continueTransactions) {
println("\nSelect an option:")
println("1. Check Balance")
println("2. Deposit")
println("3. Withdraw")
println("4. Exit")
print("Enter your choice: ")
val choice = readLine()?.toIntOrNull()
when (choice) {
1 -> println("Current Balance: $${account.balance}")
2 -> {
print("Enter deposit amount: ")
val amount = readLine()?.toDoubleOrNull()
if (amount != null && amount > 0) {
account.balance += amount
println("Deposited: $$amount")
println("New Balance: $${account.balance}")
} else {
println("Invalid amount!")
}
}
3 -> {
print("Enter withdrawal amount: ")
val amount = readLine()?.toDoubleOrNull()
if (amount != null && amount > 0) {
if (amount <= account.balance) {
account.balance -= amount
println("Withdrawn: $$amount")
println("New Balance: $${account.balance}")
} else {
println("Insufficient funds!")
}
} else {
println("Invalid amount!")
}
}
4 -> {
continueTransactions = false
println("Thank you for using Kotlin Bank!")
}
else -> println("Invalid choice! Please try again.")
}
}
}
fun main() {
bankingSimulation()
}
data class Student(val name: String, val grade: Int)
fun processStudentGrades() {
val students = mutableListOf<Student>()
var addingStudents = true
println("Student Grade Processing System")
// Input phase
while (addingStudents) {
print("Enter student name (or 'done' to finish): ")
val name = readLine()?.trim()
if (name.isNullOrEmpty() || name.lowercase() == "done") {
addingStudents = false
continue
}
print("Enter grade for $name: ")
val grade = readLine()?.toIntOrNull()
if (grade != null && grade in 0..100) {
students.add(Student(name, grade))
println("Added: $name with grade $grade")
} else {
println("Invalid grade! Please enter a number between 0 and 100.")
}
}
// Processing phase
if (students.isNotEmpty()) {
println("\n--- Grade Analysis ---")
var index = 0
var totalGrades = 0
var highestGrade = 0
var lowestGrade = 100
var highestStudent = ""
var lowestStudent = ""
while (index < students.size) {
val student = students[index]
totalGrades += student.grade
if (student.grade > highestGrade) {
highestGrade = student.grade
highestStudent = student.name
}
if (student.grade < lowestGrade) {
lowestGrade = student.grade
lowestStudent = student.name
}
println("${student.name}: ${student.grade} (${getGradeLetter(student.grade)})")
index++
}
val averageGrade = totalGrades.toDouble() / students.size
println("\n--- Summary ---")
println("Total Students: ${students.size}")
println("Average Grade: %.2f".format(averageGrade))
println("Highest Grade: $highestStudent ($highestGrade)")
println("Lowest Grade: $lowestStudent ($lowestGrade)")
} else {
println("No students added.")
}
}
fun getGradeLetter(grade: Int): String {
return when {
grade >= 90 -> "A"
grade >= 80 -> "B"
grade >= 70 -> "C"
grade >= 60 -> "D"
else -> "F"
}
}
fun main() {
processStudentGrades()
}
The Kotlin while loop is a powerful control structure that provides flexible iteration capabilities. Remember these essential points:
falseMaster these while loop Kotlin concepts to write more efficient, readable code in your Android applications and other Kotlin projects. The examples provided demonstrate real-world applications that you can adapt for your specific programming needs.