swift

find-sum-of-digits()

Parameters: number: Int

A positive integer whose digits will be summed

Returns: Sum of all digits in the provided number (Int)

This Swift function allows you to calculate the sum of all the digits of a given number. It splits the number into digits and adds them.

Variables
Arithmetic Operators
Loops
Medium dificulty

Creating a Swift Function to Sum the Digits of a Number

Hello programmer, welcome to this blog post. We aim to keep it simple and accessible for all, irrespective of the region you come from. In the steps, coming up, we'll be walking through creating a function in Swift that calculates the sum of digits in a number. This fundamental task in programming showcases the control flow and arithmetic operations. Stay with us!

Step 1: Understand the Task

Our task is to create a function in Swift which will find the sum of digits of a given number.

Let's consider an example number, 123. The sum of its digits would be 1 + 2 + 3 = 6.

We will achieve this task by repeatedly dividing the number by 10 and adding the rightmost digit to our sum until the number becomes 0.

swift
let number = 123
var sum = 0

Step 2: Begin the Loop

Let's start a while loop which continues until the number is not zero.

We don't know beforehand how many digits the number will have, hence a while loop is a good choice for such scenarios.

swift
while number > 0 {
  // Calculate the sum of digits
}

Step 3: Extract Rightmost Digit and Add to Sum

Inside the loop, we will calculate the rightmost digit of the number using the modulo operation. We then add this digit to our sum.

swift
while number > 0 {
  let digit = number % 10
  sum += digit
}

Step 4: Remove Rightmost Digit

To remove the rightmost digit from the number, we will divide the number by 10.

swift
while number > 0 {
  let digit = number % 10
  sum += digit
  number /= 10
}

Conclusion

The Swift code implementation of our function to find the sum of digits for a given number is as follow:

swift
var number = 123
var sum = 0
while number > 0 {
  let digit = number % 10
  sum += digit
  number /= 10
}
print(sum) \ The output will be 6

In the end, the variable sum holds the sum of all the digits of the original number.

Learn function in:

Digit Sum

Calculates the sum of all digits in a given number

Learn more

Mathematical principle

The find-sum-of-digits function uses basic arithmetic to add up the digits of a number. Each digit of the number is extracted by modulating the number by 10 and removing the last digit by dividing by 10 until the entire number is processed. The modulus operation is denoted as `%` in Swift.

Learn more