Kotlin Training Program

DOWNLOAD APP

FEEDBACK

while & do-while Loop

while & do-while loops are the most powerful loops of all, where we have complete control over the loop execution. We provide a condition and the loop runs till the time the condition holds true. Syntax :

 // while loop
while (/* Condition */) {
    // Code
}

// do-while loop
do {
    // Code
} while (/* Condition */)
 

The only difference between the two loops is that while loop checks the condition before every execution whereas do-while loop checks the condition after every execution. Hence, do-while loop runs at least once but while loop may or may not run, depending on the condition.

When to use?

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.

Usecase of do-while loop

do-while has a special property that it runs at least once. Here is a usecase where we need exactly that!

When we need to input an Int from user, user may enter invalid inputs like abc, 12r, 12.1. If an invalid input is entered, user will have to re-run the program for another attempt. Can we improve the UX here i.e. avoid the re-run of program when invalid input is entered? Yes we can!

 fun inputInt(): Int {
    do {
        print("Enter an integer : ")
        val input = readLine()?.toIntOrNull()

        input?.let { return it }

        println("Invalid input!")
    } while (true)
}
 

Note :

Using the inputInt() function :

 fun main() {
    val num = inputInt()
    println("\nEntered number : $num")
}

fun inputInt(): Int {
    do {
        print("Enter an integer : ")
        val input = readLine()?.toIntOrNull()

        input?.let { return it }

        println("Invalid input!")
    } while (true)
}

/* Output :

Enter an integer : abc
Invalid input!
Enter an integer : 12r
Invalid input!
Enter an integer : 12.1
Invalid input!
Enter an integer : 12

Entered number : 12
 */