Kotlin While Loop

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.

Basic Kotlin While Loop Syntax

The Kotlin while loop syntax is straightforward and intuitive. Here’s the fundamental structure:

while (testExpression) {  
    // Loop body  
    // Code to execute repeatedly  
}  

Key Components:

  • while keyword: Initiates the loop structure
  • testExpression: Boolean condition that determines loop continuation
  • Loop body: Code block executed when condition is true

Let’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  

Kotlin While Loop Properties and Characteristics

1. Pre-condition Testing

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")  
}  

2. Variable Scope

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  
}  

3. Infinite Loop Potential

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  
    }  
}  

4. Loop Control Statements

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++  
    }  
}  

Advanced While Loop Examples

Processing Collections

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++  
    }  
}  

User Input Validation

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")  
}  

Mathematical Calculations

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  
}  

Kotlin Do-While Loop vs While Loop

While the standard Kotlin while loop checks the condition before execution, the do-while loop executes the body at least once:

Do-While Syntax:

do {  
    // Code block  
} while (condition)  

Comparison Example:

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)  
}  

Common While Loop Patterns

Counter-Based Loops

fun counterPattern() {  
    var i = 0  
    while (i < 10) {  
        println("Counter: $i")  
        i += 2 // Increment by 2  
    }  
}  

Condition-Based Processing

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++  
    }  
}  

Resource Processing

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++  
    }  
}  

Complete Working Examples

Example 1: Number Guessing Game

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()  
}  

Example 2: Banking Application Simulation

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()  
}  

Example 3: Data Processing Application

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()  
}  

Key Takeaways

The Kotlin while loop is a powerful control structure that provides flexible iteration capabilities. Remember these essential points:

  • Pre-condition checking: The condition is evaluated before each iteration
  • Proper loop control: Always ensure the loop condition can become false
  • Variable management: Be mindful of variable scope and initialization
  • Performance considerations: While loops can be more efficient than other loop types for certain scenarios
  • Error prevention: Implement proper input validation and boundary checks

Master 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.