In this tutorial, you shall learn how to write a program to find the sum of digits in a given number in Kotlin.

Kotlin Sum of Digits Program

To find the sum of digits in a given number in Kotlin, iterate over the digits of the number, and accumulate the sum.

To iterate over the digits of a number, you can use while loop statement, where we divide the number by 10, and get the remainder, which is a digit from the number, and then update the number with the quotient of given number divided by 10.

Program

In the following program, we read a number from user and store it in num, then find the sum of the digits in the number, and finally print the sum to output.

Main.kt

fun main() {
    print("Enter an integer : ")
    val num = readLine()!!.toInt()

    var sum = 0
    var temp = num
    while (temp != 0) {
        val digit = temp % 10
        sum += digit
        temp /= 10
    }

    println("The sum of digits in $num is $sum.")
}

Output #1

Enter an integer : 245212
The sum of digits in 245212 is 16.

Output #2

Enter an integer : 123456
The sum of digits in 123456 is 21.

Related tutorials for the above program

Conclusion

In this Kotlin Tutorial, we learned how to find the sum of digits in a given number.