On this mastery I will show you what is recursion in C++ and how to use it.

Recursion is a form where a function calls itself. When you call the same function, you are doing a loop, and you have to give a condition in order to make this loop stop.

Let’s create the same program we did on mastery 20 but now using recursion and a function.

So, do as follows:

  1. Create a function of type long (this allows us to have bigger outputs of the numbers) and add a n variable to it.
  2. Create an if and else if condition as we learn on masteries 15 & 16
  3. If n equals to 0, factorial = 1. (That’s a rule)
  4. Else if, n multiplied by factorial of (n-1). [This is the recursion part of the program, we are calling the function inside the function n times and subtracting 1 every time the loop is done, and it will stop until n equals to 0.]
  5. Inside int main (), declare a variable and ask the user for it, then simply call the function.

Your program should look something like this:

image

Now let’s test the program. Factorial of 5 should be equal to 120.

image

And that’s about it, you just learned how to use recursion with a function, congrats!

CC BY 4.0 Mastery 21 by Omar Peza is licensed under a Creative Commons Attribution 4.0 International License.