w3resource

Kotlin recursive function: Sum of digits of a positive integer


Write a Kotlin recursive function to calculate the sum of the digits of a positive integer.


Pre-Knowledge (Before You Start!)

Before solving this exercise, you should understand these concepts:

  • Recursion: Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem. A base case is required to prevent infinite recursion.
  • Modulus and Integer Division: The modulus operator (%) helps extract the last digit of a number, while integer division (/) removes the last digit.
  • Base Case in Recursion: A recursive function must have a base case to stop the recursion. For summing digits, the base case is when the number has only one digit.
  • Recursive Case: The function should break the problem into smaller parts by extracting the last digit and recursively processing the remaining number.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: Define a function that takes an integer as input and returns the sum of its digits.
  • Hint 2: Use an if statement to check if the number is a single-digit value (base case).
  • Hint 3: Use the modulus operator (%) to get the last digit and integer division (/) to remove it.
  • Hint 4: Call the function recursively on the remaining part of the number and add the last digit.

Sample Solution:

Kotlin Code:

fun calculateSumOfDigits(number: Int): Int {
    return if (number < 10) {
        number
    } else {
        val lastDigit = number % 10
        val remainingDigits = number / 10
        lastDigit + calculateSumOfDigits(remainingDigits)
    }
}

fun main() {
    val number = 12345678
    val sum = calculateSumOfDigits(number)
    println("Sum of digits of $number: $sum")
}

Sample Output:

Sum of digits of 12345678: 36

Explanation:

In the "calculateSumOfDigits()" function, we check if the number is less than 10. If it is, we simply return the number itself as a single digit. Otherwise, we calculate the last digit of the number using the modulus operator % and the remaining digits by dividing the number by 10. We recursively call the "calculateSumOfDigits()" function with the remaining digits and add the last digit to it. This process continues until the number becomes less than 10, and we eventually get the sum of all the digits.

Kotlin Editor:


Previous: Kotlin Recursion Function Exercises Home.
Next: Calculate the power of a number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.