English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to calculate the number of digits of an integer

Kotlin Complete Examples

In this program, you will learn how to use the while loop in Kotlin to calculate the number of digits of a number.

Example1:Calculate the number of digits in an integer

fun main(args: Array<String>) {
    var count = 0
    var num = 1234567
    while (num != 0) {
        num /= 10
        ++count
    }
    println("The number of digits: \t$count")
}

When running this program, the output will be:

Number of digits: 7

In this program, the loop will be executed using a while loop until the test expression num != 0 evaluates to 0 (false).

  • After the first iteration, num will be divided by10, its value will be345. Then, count will be incremented to1.

  • After the second iteration, the value of num will be34, and count will be incremented to2.

  • After the third iteration, the value of num will be3, and count will be incremented to3.

  • After the fourth iteration, the value of num will be 0, and count will be incremented to4.

  • Then evaluate the test expression to false and terminate the loop.

The following is the equivalent Java code:Java Program to Calculate the Number of Digits in an Integer

Kotlin Complete Examples