Recursion is a computational approach where a method calls itself from within its body. Programmers use recursion when they need to perform the same action multiple times in a row until it reaches a predefined stopping point, also known as a base case.
Take a look at the **Factorial.swift**
file to the right where we have the beginning of a recursive implementation of a factorial.
Within the function, we check whether a condition is met. If it is, then we print the value of n
and return a call to findFactorialRecursively(n - 1)
. If the condition is not met, we return 0
.
If you run the code now, you’ll see the following output:
Execution context: 4 Execution context: 3 Execution context: 2 Execution context: 1 0
The function isn’t returning the correct answer at the moment (factorial of 4 is not 0, it’s ) but it will! In this lesson, we’ll walk you through correcting the function and teach you about the intricacies of recursive functions, what a base case and recursive case are, and more. Let’s get started!
Instructions
Remove the boolean true
inside the if
statement. Replace it with something that will prevent findFactorialRecursively()
from calling itself if n
is less than 1
.