Mark As Completed Discussion

Factorial

Now that we understand both iteration and recursion, let's look at how both of them work.

As we know factorial of a number is defined as:

n! = n(n-1)(n-2)...1

or in other words:

n! = n(n-1)!

Let's now implement both an iterative and recursive solution for factorial in C++.

Both solutions look intuitive and easy to understand. The iterative version has a control variable i, which controls the loop so that the loop runs n times. For the iterative solution, we know in advance exactly how many times the loop would run.

The recursive version uses the second definition: n! = n * (n - 1)!, which is naturally a recursive definition. It defines the factorial of n in terms of the factorial of a smaller version (n - 1). We don't need to specify in advance, how many times the loop will run.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment