ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

While Loop in Kotlin

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='25' AND `tutorial_submenu`='84' AND `tutorial_status`=1 LIMIT 1

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

kotlin

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.

kotlin

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:

kotlin

var count = 0do { println("Count: $count") count++} while (count < 3)

Output:

makefile

Count: 0Count: 1Count: 2


✅ Difference Between while and do-while

Featurewhile Loopdo-while Loop
Condition CheckBefore executing the loop bodyAfter executing the loop body
Minimum Execution0 times if the condition is falseAt least once, even if the condition is false
UsageWhen the condition may not be true initiallyWhen the loop body needs to run at least once


✅ Conclusion

  • Use while if the loop might not execute at all.

  • Use do-while when you need to ensure the loop runs at least once.

  • Ensure you update variables inside the loop to avoid infinite loops.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql