Recursion is a powerful tool for solving problems that require the execution of an action multiple times until a condition is met. For many problems, a recursive solution will result in fewer lines of code and will be easier to comprehend than a solution that uses a for
or while
loop.
You may find that recursion is a difficult concept to wrap your head around at first. That’s fine! This lesson is meant as an introduction. As you see more examples and get more practice, you will start to feel comfortable with the concept.
In this lesson, you will learn to implement a recursive function that returns the factorial of a number. An integer’s factorial is the product of an integer and all the positive numbers less than it.
Let’s consider 4 factorial denoted by 4!
:
4! = 4 × 3 × 2 × 1 = 24
Four factorial is equal to the product of 4 x 3 x 2 x 1
, which is 24
. The exclamation mark denotes that the number 4
is being factorialized.
Note: 1!
and 0!
are both valid base cases of factorial. The factorial product of both numbers is 1
.
Before we dive into recursion, let’s consider how a factorial is implemented with an iterative approach.
Instructions
Factorial.swift includes a function called .findFactorialIteratively()
. The function accepts an integer as an argument and returns its factorial.
Take a look at how we implemented the function. Run the code when you’re ready to move on.
Set a variable named fourFactorial
equal to the value returned from findFactorialIteratively()
, with 4
as the argument. Print fourFactorial
on the following line to see the final outcome of the function.