Kotlin recursive function: Sum of digits of a positive integer
Kotlin Function: Exercise-1 with Solution
Write a Kotlin recursive function to calculate the sum of the digits of a positive integer.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/kotlin-exercises/recursion-function/kotlin-recursion-function-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics