Scala program to find the sum of digits of a number

1. Introduction

Finding the sum of digits of a number is a common programming task. For instance, if we have the number 123, the sum of its digits is 1 + 2 + 3 = 6. This blog post presents a Scala program that calculates the sum of the digits of a given number.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define the number whose digits' sum needs to be found.

4. Implement a function to compute the sum of the digits.

5. Call the sum-calculation function and display the result.

6. Run the program.

3. Code Program

object DigitSumApp {
  def main(args: Array[String]): Unit = {
    // Define the number
    val num = 12345

    println(s"Finding the sum of digits of the number: $num")

    // Calculate and print the sum using the sumOfDigits function
    val result = sumOfDigits(num)
    println(s"\nThe sum of digits of $num is: $result")
  }

  // Function to determine the sum of digits of a number
  def sumOfDigits(n: Int): Int = {
    if (n == 0) 0 else n % 10 + sumOfDigits(n / 10)
  }
}

Output:

Finding the sum of digits of the number: 12345
The sum of digits of 12345 is: 15

Explanation:

1. We start with an object named DigitSumApp. In Scala, the main method, which is the program's entry point, is housed within an object.

2. Within the main function, we declare a value num representing the number for which we want to find the sum of digits.

3. We inform the user about the number being processed.

4. The sumOfDigits function calculates the sum of digits of the given number. This is done recursively: at each step, the last digit is added (n % 10), and the function is called again with the number excluding its last digit (n / 10).

5. The main function invokes the sumOfDigits function to get the sum of digits and subsequently displays the result.

6. The output section displays the number being processed and its sum of digits.


Comments