Home » Swift Recursion

Swift Recursion

A function that calls itself repeatedly is known as recursive function and this technique is called recursion. When you create a recursive function, you must create a condition so that the function does not call itself indefinitely.

Example:

Swift Recursion

You can see in the above diagram that recursion is executed indefinitely. To get rid of these type of indefinite recursive, we use control statements.

Example: Swift 4 Program to print N positive numbers

Output:

Countdown:  6  5  4  3  2  1  0  

You can see in the above program that the statement print(“Countdown:”) gives the output and the statement countDownToZero(num:3) calls the function that takes a parameter Integer.

The statement inside the function countDownToZero() executes and if the condition num > 0 is fulfilled, the function countDownToZero() is called again as countDownToZero(num: num – 1).

When the condition is not fulfilled, the function call is not done and the recursion stops.

Execution Steps

Steps Function call Printed Is num > 0 ?
1 countDownToZero(6) 6 Yes
2 countDownToZero(5) 5 Yes
3 countDownToZero(4) 4 Yes
4 countDownToZero(3) 3 Yes
5 countDownToZero(2) 2 Yes
6 countDownToZero(1) 1 Yes
7 countDownToZero(0) 0 No (Recursion Ends)

Example2: Swift 4 program to find factorial of a number

Output:

The factorial of 6 is 720  

Execution Steps

Steps Argument passed Return statement Value
1 6 return 6 * findFactorial(of:5) 6 * findFactorial(of:5)
2 5 return 5 * findFactorial(of:4) 6 *5 findFactorial(of:4)
3 4 return 4 * findFactorial(of:3) 6 *5*4 findFactorial(of:3)
4 3 return 3 * findFactorial(of:2) 6 *5*4*3 findFactorial(of:2)
5 2 return 2 * findFactorial(of:1) 6*5*4*3*2 findFactorial(of:1)
6 1 return 1 6*5*4*3*2*1

You may also like