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


What Does it Mean to Find the Sum of Digits?

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

  • The sum of digits of 12345 is 1 + 2 + 3 + 4 + 5 = 15.
  • The sum of digits of -678 is 6 + 7 + 8 = 21 (ignoring the sign).
  • The sum of digits of 0 is 0.

We will use a mathematical approach to extract and sum each digit of the number.


Algorithm to Find the Sum of Digits

To calculate the sum of the digits of a number, follow these steps:

  1. Take the absolute value of the number to handle negative numbers.
  2. Initialize a variable sum to 0 to store the sum of digits.
  3. Use a loop to extract each digit:
    1. Extract the last digit using modulus operation (% 10).
    2. Add the digit to sum.
    3. Remove the last digit using integer division (/ 10).
  4. Repeat the process until the number becomes 0.
  5. Return the final value of sum.

This algorithm ensures that each digit of the number is processed exactly once to calculate the sum efficiently.


Step-by-Step Implementation in Swift

Let’s implement the algorithm in Swift step by step.

1. Handle Negative Numbers

Create a function that takes the absolute value of the number to handle negative inputs:

</>
Copy
func sumOfDigits(_ number: Int) -> Int {
    var num = abs(number) // Handle negative numbers
    var sum = 0           // Initialize the sum
    return sum            // Placeholder for further steps
}

2. Extract and Sum Each Digit

Use a loop to extract each digit, add it to the sum, and remove the last digit:

</>
Copy
func sumOfDigits(_ number: Int) -> Int {
    var num = abs(number) // Handle negative numbers
    var sum = 0           // Initialize the sum
    
    while num > 0 {
        let digit = num % 10 // Extract the last digit
        sum += digit         // Add the digit to the sum
        num /= 10            // Remove the last digit
    }
    
    return sum // Return the total sum
}

Explanation:

var num = abs(number): Handles negative numbers by taking the absolute value.

let digit = num % 10: Extracts the last digit of the number.

sum += digit: Adds the digit to the running total.

num /= 10: Removes the last digit from the number.

return sum: Returns the total sum after the loop ends.

3. Test the Function

Let’s test the function with some example inputs:

</>
Copy
// Test cases
print("Sum of digits in 12345: \(sumOfDigits(12345))") // 15
print("Sum of digits in -678: \(sumOfDigits(-678))")   // 21
print("Sum of digits in 0: \(sumOfDigits(0))")         // 0

The function calculates the sum of digits for positive and negative numbers, as well as zero.


Complete Swift Program

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

main.swift

</>
Copy
import Foundation

// Function to find the sum of the digits of a number
func sumOfDigits(_ number: Int) -> Int {
    var num = abs(number) // Handle negative numbers
    var sum = 0           // Initialize the sum
    
    while num > 0 {
        let digit = num % 10 // Extract the last digit
        sum += digit         // Add the digit to the sum
        num /= 10            // Remove the last digit
    }
    
    return sum // Return the total sum
}

// Test cases
print("Sum of digits in 12345: \(sumOfDigits(12345))") // 15
print("Sum of digits in -678: \(sumOfDigits(-678))")   // 21
print("Sum of digits in 0: \(sumOfDigits(0))")         // 0

Output

</>
Copy
Sum of digits in 12345: 15
Sum of digits in -678: 21
Sum of digits in 0: 0

Screenshot from Xcode

Swift Program to Find the Sum of Digits of a Number