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:

- Email

- 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

🧠 Test Your Knowledge

How many times will this loop run?
var i = 5; while (i > 0) { println(i); i-- }