Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
In Kotlin, the while
loop is a control flow structure that allows you to repeatedly execute a block of code as long as a specified condition is true. There's also a variation called the do-while
loop. This tutorial will introduce you to both of these loops.
while
LoopSyntax:
while (condition) { // code to be executed }
The loop will keep executing as long as the condition remains true
.
Example:
var counter = 5 while (counter > 0) { println("Counter value: $counter") counter-- }
Output:
Counter value: 5 Counter value: 4 Counter value: 3 Counter value: 2 Counter value: 1
do-while
LoopThe do-while
loop is similar to the while
loop but with a key difference: it checks the condition after executing the loop body. This means the loop body will always execute at least once.
Syntax:
do { // code to be executed } while (condition)
Example:
var counter = 5 do { println("Counter value: $counter") counter-- } while (counter > 0)
Output:
Counter value: 5 Counter value: 4 Counter value: 3 Counter value: 2 Counter value: 1
Beware of Infinite Loops: If the condition in your while
or do-while
loop never becomes false
, the loop will run indefinitely. This can lead to the program becoming unresponsive.
Prefer For-Loops for Known Iterations: If you know beforehand how many times you want to execute a loop (e.g., iterating over a collection or range), a for
loop is often a more suitable choice.
Use do-while
for Post-Check Iteration: If you have a scenario where you want to ensure the loop body is executed at least once (e.g., a menu system where you prompt a user at least once before checking their input), the do-while
loop is ideal.
Keep Loop Bodies Small: For clarity and maintainability, try to keep the body of your loops concise. If the loop's logic becomes complex, consider refactoring some of that logic into separate functions.
The while
and do-while
loops in Kotlin provide you with tools for creating iterations based on conditions. Understanding how and when to use them can help you craft efficient and readable programs. Remember to always be cautious of conditions that may lead to infinite loops and to choose the loop structure that best matches your specific needs.
while
loop in Kotlin:The while
loop in Kotlin allows you to repeatedly execute a block of code while a condition is true.
fun main() { var count = 0 while (count < 5) { println("Count: $count") count++ } }
while
loops and exit conditions in Kotlin:Be cautious with infinite loops. Ensure there is an exit condition to prevent an infinite loop.
fun main() { var count = 0 while (true) { println("Count: $count") count++ if (count >= 5) { break } } }
break
and continue
in while
loops in Kotlin:You can use break
to exit the loop and continue
to skip the rest of the current iteration.
fun main() { var count = 0 while (count < 5) { if (count == 2) { count++ continue } println("Count: $count") if (count == 3) { break } count++ } }
Do-while
vs while
loop in Kotlin:The do-while
loop guarantees that the block of code is executed at least once, as the condition is checked after the first iteration.
fun main() { var count = 0 do { println("Count: $count") count++ } while (count < 5) }
while
loops in Kotlin:You can nest while
loops to create more complex iteration patterns.
fun main() { var outer = 0 while (outer < 3) { var inner = 0 while (inner < 2) { println("Outer: $outer, Inner: $inner") inner++ } outer++ } }
while
loops:You can use logical operators to create complex conditions in while
loops.
fun main() { var count = 0 while (count < 10 && count % 2 == 0) { println("Count: $count") count += 2 } }
While
loop and user input in Kotlin:You can use a while
loop to repeatedly ask for user input until a specific condition is met.
fun main() { var userInput: String while (true) { print("Enter 'exit' to quit: ") userInput = readLine() ?: "" if (userInput.toLowerCase() == "exit") { break } } println("Exited the loop") }
while
loop for computations in Kotlin:while
loops can be used for iterative computations.
fun main() { var factorial = 1 var n = 5 while (n > 0) { factorial *= n n-- } println("Factorial: $factorial") }
while
loops in Kotlin:Handle errors or unexpected input within a while
loop.
fun main() { var userInput: Int while (true) { try { print("Enter a number: ") userInput = readLine()?.toInt() ?: throw NumberFormatException("Invalid input") println("Square: ${userInput * userInput}") break } catch (e: NumberFormatException) { println("Invalid input. Please enter a valid number.") } } }
While
loop and lists/arrays in Kotlin:Iterate over elements in a list or array using a while
loop.
fun main() { val numbers = listOf(1, 2, 3, 4, 5) var index = 0 while (index < numbers.size) { println("Element at index $index: ${numbers[index]}") index++ } }