Swift program to find sum of digits of a number using recursion

SwiftServer Side ProgrammingProgramming

Swift 4 Online Training

38 Lectures 1 hours

Swift Basics: Learn to Code from Scratch [For Beginners]

13 Lectures 2 hours

How to create Tic-Tac-Toe Game for iPhone using Swift in Xcode - iOS App

7 Lectures 1 hours

This tutorial will discuss how to write swift program to find the sum of digits of a number using recursion.

Recursion is a process in which a function call itself directly or indirectly to solve some specific task or problem. Using recursion, we can also find the sum of digits of a given number.

Below is a demonstration of the same −

Suppose our given input is −

Number = 1298


The desired output would be −

Sum = 20


Here the sum is 20 because 1 + 2 + 9 + 8 = 20

Algorithm

Following is the algorithm −

• Step 1− Declare a variable with 0 as an initial value. This variable is used to store the sum.

• Step 2− Create a recursive function.

• Step 3− Set the base condition using if else statement to stop the recession process. The condition is −

if (m > 0)

• Step 4− Now we find the sum of dig its of the number.

msum = msum + (m % 10)
return digitSum(m: m / 10)

• Step 5− Return the sum

• Step 6− Declare a variable to store number. Here the value of this variable can be user defined or pre-defined.

• Step 7− Call the function and pass this variable to the function.

• Step 8− Display output.

Example

The following program shows how to find the sum of digits of a number using recursion.

import Foundation
import Glibc

var msum: Int = 0

// Function to find the sum of the digits
// in the number using recursion
func digitSum(m: Int) -> Int{

// Base condition
if (m > 0) {
msum = msum + (m % 10)
return digitSum(m: m / 10)
}
return msum
}
var number = 336
print("Sum of digits of \(number):", digitSum(m: number))


Output

Sum of digits of 336: 12


Here in the above code, we create a recursive function named digitSum(). In this function, we calculate the sum of digits present in the given number by calling the function itself. Here the number is 336 so the working of the digitSum() function is −

1st call with 336: digitSum(m: 336):

if (336 > 0) //true{
msum = 2 + (336 % 10) = 6 + 3 = 9
return digitsum(m:m/10) = digitsum(m:33/10)=33
}


2nd call with 33: digitSum(m: 33):

if (33 > 0) //true{
msum = 2 + (33 % 10) = 6 + 3 = 9
return digitsum(m:m/10) = digitsum(m:33/10)=33
}


3rd call with 33: digitSum(m: 3):

if (3 > 0) //true{
msum = 9 + (3 % 10) = 9 + 3 = 12
return digitsum(m:m/10) = digitsum(m:3/10)=33
}


4th call with 0: digitSum(m: 0):

if (0 > 0) //false so return msum = 12


Hence the sum of digits of 336 is 12.

Updated on 10-Oct-2022 12:45:24

Advertisements