How to calculate the sum of digits in a number using Kotlin
How to calculate the sum of digits in a number using Kotlin.
Here's a detailed step-by-step tutorial on how to calculate the sum of digits in a number using Kotlin:
- First, let's create a function called
calculateSumOfDigitsthat takes an integer number as a parameter and returns the sum of its digits. We'll use recursion to solve this problem.
fun calculateSumOfDigits(number: Int): Int {
// Base case: if the number is less than 10, return the number itself
if (number < 10) {
return number
}
// Recursive case: recursively call the function with the sum of the digits
return number % 10 + calculateSumOfDigits(number / 10)
}
- Now, let's test our function by calling it with different numbers. We'll print the result to the console.
fun main() {
val number1 = 123
val sum1 = calculateSumOfDigits(number1)
println("The sum of digits in $number1 is $sum1")
val number2 = 4567
val sum2 = calculateSumOfDigits(number2)
println("The sum of digits in $number2 is $sum2")
val number3 = 987654321
val sum3 = calculateSumOfDigits(number3)
println("The sum of digits in $number3 is $sum3")
}
Output:
The sum of digits in 123 is 6
The sum of digits in 4567 is 22
The sum of digits in 987654321 is 45
In the above code, we first define three different numbers (number1, number2, number3) and call the calculateSumOfDigits function with each number. The returned sum is then printed to the console along with the original number.
The calculateSumOfDigits function works by first checking if the number is less than 10. If it is, we simply return the number itself as the sum of its digits. Otherwise, we use the modulus operator (%) to get the last digit of the number and add it to the sum of the remaining digits. We achieve this by recursively calling the calculateSumOfDigits function with the number divided by 10 (to remove the last digit).
By following these steps, you can easily calculate the sum of digits in a number using Kotlin.