Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Kotlin Program to Count Number of Digits in an Integer
In this program, you'll learn to count the number of digits using a while loop in Kotlin.
Example 1: Count Number of Digits in an Integer
fun main(args: Array<String>) {
var count = 0
var num = 1234567
while (num != 0) {
num /= 10
++count
}
println("Number of digits: $count")
}
When you run the program, the output will be:
Number of digits: 7
In this program, while loop is iterated until the test expression num != 0 is evaluated to 0 (false).
- After first iteration, num will be divided by 10 and its value will be 345. Then, the count is incremented to 1.
- After second iteration, the value of num will be 34 and the count is incremented to 2.
- After third iteration, the value of num will be 3 and the count is incremented to 3.
- After fourth iteration, the value of num will be 0 and the count is incremented to 4.
- Then the test expression is evaluated to false and the loop terminates.
Here's the equivalent Java code: Java Program to Count Number of Digits in an Integer
Did you find this article helpful?