Swift – Find Sum of Digits of a Number using Recursion

In this tutorial, we will learn how to find the sum of the digits of a number using recursion in Swift. We will understand the concept, write an algorithm, and implement the solution step by step with a complete Swift program and output.


Understanding the Problem

Finding the sum of the digits of a number involves adding all its digits together. For example:

  • The sum of digits of 123 is 1 + 2 + 3 = 6.
  • The sum of digits of -456 is 4 + 5 + 6 = 15 (ignoring the sign).
  • The sum of digits of 0 is 0.

We will use recursion to break down the problem into smaller subproblems and add the digits until the number becomes 0.


Algorithm to Find Sum of Digits Using Recursion

  1. Take the number as input.
  2. Base Case: If the number is 0, return 0.
  3. Recursive Case:
    1. Extract the last digit using number % 10.
    2. Add it to the result of the recursive call for number / 10.

This algorithm processes each digit of the number recursively until the base case is reached.


Step-by-Step Implementation in Swift

1. Define the Base Case

Create a function that returns 0 when the input number is 0:

</>
Copy
func sumOfDigits(_ number: Int) -> Int {
    if number == 0 {
        return 0 // Base case: Return 0 if the number is 0
    }
    return 0 // Placeholder for recursive case
}

2. Add the Recursive Case

Add logic to calculate the last digit and recursively call the function for the rest of the number:

</>
Copy
func sumOfDigits(_ number: Int) -> Int {
    let num = abs(number) // Handle negative numbers
    if num == 0 {
        return 0 // Base case
    }
    return (num % 10) + sumOfDigits(num / 10) // Recursive case
}

Explanation:

  • abs(number): Ensures that the function works for negative numbers by taking the absolute value.
  • num % 10: Extracts the last digit of the number.
  • num / 10: Removes the last digit from the number.
  • (num % 10) + sumOfDigits(num / 10): Adds the last digit to the sum of the digits of the remaining number.

3. Test the Function

Let’s test the function with some example inputs:

</>
Copy
// Test cases
print("Sum of digits in 123: \(sumOfDigits(123))")    // Output: 6
print("Sum of digits in -456: \(sumOfDigits(-456))")  // Output: 15
print("Sum of digits in 0: \(sumOfDigits(0))")        // Output: 0

Complete Swift Program

Here’s the complete Swift program to find the sum of the digits of a number using recursion:

main.swift

</>
Copy
import Foundation

// Recursive function to find the sum of digits of a number
func sumOfDigits(_ number: Int) -> Int {
    let num = abs(number) // Handle negative numbers
    if num == 0 {
        return 0 // Base case
    }
    return (num % 10) + sumOfDigits(num / 10) // Recursive case
}

// Test cases
print("Sum of digits in 123: \(sumOfDigits(123))")    // Output: 6
print("Sum of digits in -456: \(sumOfDigits(-456))")  // Output: 15
print("Sum of digits in 0: \(sumOfDigits(0))")        // Output: 0

Output:

Sum of digits in 123: 6
Sum of digits in -456: 15
Sum of digits in 0: 0
Program ended with exit code: 0

Xcode Screenshot:

Swift Program to Find Sum of Digits of a Number using Recursion