while
& do-while
loops are to be used when the exact number of loop iterations is unknown. Example - Program to find whether a number is Palindrome :
fun main() {
print("Enter a number : ")
val num = readLine()!!.toInt()
val reverse = reverse(num)
if (num == reverse)
println("$num is a Palindrome!")
else
println("$num is not a Palindrome!")
}
private fun reverse(num: Int): Int {
var quotient = num
var remainder: Int
var reverse = 0
while (quotient != 0) {
remainder = quotient % 10
quotient /= 10
reverse = reverse * 10 + remainder
}
return reverse
}
To find whether a number is Palindrome, we first evaluate the reverse of the number. To evaluate the reverse of a number, we repeatedly divide it by 10, take the remainder and use it to form the reverse. For this we do not know the exact number of iterations, hence while
loop is the best candidate.