0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Find Sum of Digits Using Recursion

You can find the sum of digits in Kotlin using recursion by defining a function like fun sumOfDigits(n: Int): Int = if (n == 0) 0 else n % 10 + sumOfDigits(n / 10) which adds the last digit to the sum of the remaining digits recursively.
📋

Examples

Input123
Output6
Input0
Output0
Input9999
Output36
🧠

How to Think About It

To find the sum of digits using recursion, think of the number as a collection of digits. Take the last digit using n % 10, then call the same function on the number without the last digit using n / 10. Keep adding these digits until the number becomes zero, which stops the recursion.
📐

Algorithm

1
Check if the number is zero; if yes, return zero as the sum.
2
Extract the last digit of the number using modulo 10.
3
Call the function recursively with the number divided by 10 (removing the last digit).
4
Add the last digit to the result of the recursive call.
5
Return the total sum.
💻

Code

kotlin
fun sumOfDigits(n: Int): Int {
    return if (n == 0) 0 else n % 10 + sumOfDigits(n / 10)
}

fun main() {
    val number = 123
    println("Sum of digits of $number is ${sumOfDigits(number)}")
}
Output
Sum of digits of 123 is 6
🔍

Dry Run

Let's trace sumOfDigits(123) through the code

1

Initial call

n = 123, n != 0, last digit = 3, call sumOfDigits(12)

2

Second call

n = 12, n != 0, last digit = 2, call sumOfDigits(1)

3

Third call

n = 1, n != 0, last digit = 1, call sumOfDigits(0)

4

Base case

n = 0, return 0

5

Returning from third call

return 1 + 0 = 1

6

Returning from second call

return 2 + 1 = 3

7

Returning from initial call

return 3 + 3 = 6

CallnLast Digit (n % 10)Recursive Call (n / 10)Return Value
sumOfDigits(123)1233sumOfDigits(12)6
sumOfDigits(12)122sumOfDigits(1)3
sumOfDigits(1)11sumOfDigits(0)1
sumOfDigits(0)00N/A0
💡

Why This Works

Step 1: Base case stops recursion

When n becomes zero, the function returns 0 to stop further recursive calls.

Step 2: Extract last digit

Using n % 10 gets the last digit of the number to add to the sum.

Step 3: Recursive call reduces problem size

Calling sumOfDigits(n / 10) removes the last digit, making the problem smaller each time.

Step 4: Sum accumulates on return

Each recursive call returns the sum of digits found so far, adding the last digit at each step.

🔄

Alternative Approaches

Using tail recursion
kotlin
fun sumOfDigitsTail(n: Int, acc: Int = 0): Int {
    return if (n == 0) acc else sumOfDigitsTail(n / 10, acc + n % 10)
}

fun main() {
    val number = 123
    println("Sum of digits (tail recursion) of $number is ${sumOfDigitsTail(number)}")
}
Tail recursion can be optimized by Kotlin to avoid stack overflow for large numbers.
Using iteration
kotlin
fun sumOfDigitsIterative(n: Int): Int {
    var num = n
    var sum = 0
    while (num > 0) {
        sum += num % 10
        num /= 10
    }
    return sum
}

fun main() {
    val number = 123
    println("Sum of digits (iterative) of $number is ${sumOfDigitsIterative(number)}")
}
Iterative approach uses a loop and is often more efficient in memory than recursion.

Complexity: O(log n) time, O(log n) space

Time Complexity

The function calls itself once per digit, so time grows with the number of digits, which is proportional to log base 10 of the number.

Space Complexity

Each recursive call adds a new layer to the call stack, so space used is proportional to the number of digits (log n).

Which Approach is Fastest?

Iterative approach uses constant space and is faster in practice, while recursion is elegant but uses more memory.

ApproachTimeSpaceBest For
Simple RecursionO(log n)O(log n)Learning recursion and small inputs
Tail RecursionO(log n)O(1) with optimizationLarge inputs with recursion optimization
IterativeO(log n)O(1)Performance and memory efficiency
💡
Use recursion base case to stop when number becomes zero to avoid infinite calls.
⚠️
Forgetting to reduce the number by dividing by 10 causes infinite recursion.