Log in from a computer to take this course

You'll need to log in from a computer to start Introduction to Algorithms and Linear Data Structures in Swift. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

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.

Instructions

1.

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.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?