w3resource

Scala function: Calculate the sum of digits in a number

Scala Function Exercise-3 with Solution

Write a Scala function to calculate the sum of digits in a given number.

Sample Solution:

Scala Code:

object DigitSumCalculator {
  def sumOfDigits(n: Int): Int = {
    var num = n
    var sum = 0

    while (num != 0) {
      val digit = num % 10
      sum += digit
      num /= 10
    }

    sum
  }

  def main(args: Array[String]): Unit = {
    val number = 12345678
    val sum = sumOfDigits(number)
    println(s"The sum of digits in $number is: $sum")
  }
}

Sample Output:

The sum of digits in 12345678 is: 36

Scala Code Editor :

Previous: Determine if a number is prime.
Next: Reverse a Given String.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.