In this tutorial you will learn about the Swift Recursion and its application with practical example.
Swift Recursion
Recursion is the process where a function calls itself, and the function which calls itself is know as recursive function.
Table Of Contents−
Characteristics of a recursive function
- A recursive function is a function which calls itself.
- The speed of a recursive program is slower because of stack overheads.
- A recursive function must have terminating conditions, and recursive expressions.
Advantages of Recursion
- It requires few variables which make program clean.
- It shorten the complex and nested code.
Disadvantages of Recursion
- It is hard to debug recursive function.
- It is tough to understand the logic of a recursive function.
To understand how recursion works lets have one of the popular example of recursion. In this example we will calculate the factorial of n numbers. The factorial of n numbers is expressed as a series of repetitive multiplication as shown below:
1 |
Factorial of n = n(n-1)(n-2)……1. |
Example:
1 2 |
Factiorial of 5 = 5x4x3x2x1 Equals to 120 |
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
func factorial(num: Int) -> Int { if num == 1 { return 1 } else { return num * factorial(num: num - 1) } } let result = factorial(num: 5) print("W3Adda - Swift Recursion") print("The factorial of \(5) is \(result)") |
Output:-