Skip to main content

How to calculate the sum of the digits of a number until a single digit is obtained in Kotlin

How to calculate the sum of the digits of a number until a single digit is obtained in Kotlin.

Here's a step-by-step tutorial on how to calculate the sum of the digits of a number until a single digit is obtained in Kotlin.

Step 1: Define the input number​

First, you need to define the number for which you want to calculate the sum of its digits. You can do this by assigning a value to a variable. For example:

val number = 12345

Step 2: Create a function to calculate the sum of digits​

Next, you need to create a function that takes the input number as an argument and calculates the sum of its digits. You can do this by converting the number to a string and then iterating over each character to convert it back to an integer. Here's an example implementation of the function:

fun calculateDigitSum(number: Int): Int {
var sum = 0
var num = number

while (num > 0) {
sum += num % 10
num /= 10
}

return sum
}

Step 3: Calculate the sum of digits until a single digit is obtained​

Now that you have the function to calculate the sum of digits, you can use it to repeatedly calculate the sum until a single digit is obtained. You can do this by calling the function in a loop until the result is less than 10. Here's an example implementation:

var result = number

while (result >= 10) {
result = calculateDigitSum(result)
}

println("The sum of digits of $number is $result")

Step 4: Test the code​

You can now test the code by running it with different input numbers. For example, if you run the code with the input number 12345, the output will be:

The sum of digits of 12345 is 6

Code summary​

Here's a summary of the complete code:

fun calculateDigitSum(number: Int): Int {
var sum = 0
var num = number

while (num > 0) {
sum += num % 10
num /= 10
}

return sum
}

fun main() {
val number = 12345
var result = number

while (result >= 10) {
result = calculateDigitSum(result)
}

println("The sum of digits of $number is $result")
}

And that's it! You now know how to calculate the sum of the digits of a number until a single digit is obtained in Kotlin.