Careeroza
while and do-while
while
Example
while repeats as long as the condition is true. It checks the condition before each run, so the body may run zero times.
fun main() {
var balance = 1000
var month = 0
while (balance < 1500) {
balance += balance / 10 // 10% growth
month++
}
println("Reached ₹$balance after $month months")
}Output
Reached ₹1610 after 5 months
do-while
Example
do-while checks the condition after the body, so the body always runs at least once. Useful for retries.
fun main() {
var attempt = 0
val successOn = 3
do {
attempt++
println("Connecting... attempt $attempt")
} while (attempt < successOn)
println("Connected")
var x = 100
do {
println("Runs once even though x > 10: $x")
} while (x < 10)
}Output
Connecting... attempt 1 Connecting... attempt 2 Connecting... attempt 3 Connected Runs once even though x > 10: 100