While Loop in Kotlin
📌 while Loop in Kotlin
In Kotlin, a while loop is used to execute a block of code repeatedly as long as the specified condition is true. It is generally used when the number of iterations is not known in advance.
✅ Syntax of while Loop
var i = 1while (i <= 5) { println("Iteration: $i") i++ Iteration: 1Iteration: 2Iteration: 3Iteration: 4Iteration: 5
✅ Example 2: Infinite Loop (Avoid)
If the condition never becomes false, it results in an infinite loop.
var i = 1while (true) { println("This is loop number $i") i++ import java.util.Scannerfun () { val scanner = Scanner(System.`in`) var number: Int println("Enter a number greater than 0 (0 to exit): ") number = scanner.nextInt() while (number > 0) { println("You entered: $number") println(do { // Code to execute} while (condition)
📌 Example:
var count = 0do { println("Count: $count") count++} while (count < 3)
Output:
Count: 0Count: 1Count: 2
✅ Difference Between while and do-while
| Feature | while Loop | do-while Loop |
|---|---|---|
| Condition Check | Before executing the loop body | After executing the loop body |
| Minimum Execution | 0 times if the condition is false | At least once, even if the condition is false |
| Usage | When the condition may not be true initially | When the loop body needs to run at least once |
✅ Conclusion
Use
whileif the loop might not execute at all.Use
do-whilewhen you need to ensure the loop runs at least once.Ensure you update variables inside the loop to avoid infinite loops.