Throughout this lesson, you learned about recursion as you coded a factorial method. While every recursive problem is a little different, the following features will always be required:
- Recursive case – the conditions under which the method will perform an action and call itself.
- Base case – the conditions under which the method returns a value without making any additional calls to itself.
In this example, we started by considering the recursive case. With some problems it may be easier to start with the base case. Regardless, when you are dealing with a recursive problem, start by thinking about potential recursive and base cases for your solution.
In Factorial.swift, we included both the iterative and recursive solutions to factorial. As you learn more about recursion, you may find the recursive syntax to be more readable and easier to understand when addressing certain problems. Consider it another tool in your toolbox as you approach increasingly challenging programming problems.
Change the iterative and recursive factorial functions, so the program prints the following messages:
The recursive solution to 10! is: 3628800 The iterative solution to 10! is: 3628800
Make sure you change the value of the argument passed to each function and the number in the logged string.