What is recursion?
What is a base conditional?
Recursion is the process of having a function call itself to perform a loop. There are two conditionals that make up a recursive function: the base conditional and the recursive conditional. For this example we will create a recursive method to print stars. The function declaration is:
The base conditional determines when a function should stop looping. When your function enters the base conditional it should return a value. The base conditional for the stars function is:
if x == 1:
The recursive conditional is in charge of maintaining all looping of the function. When creating the recursive conditional your goal is to end up in the base conditional. The recursive conditional for the stars function is:
When we put all these pieces of code together it looks like this:
if x == 1:
Here is a diagram showing what happens when you call stars(3):
Lets go over these questions using the diagram of stars(3):
Now that we have discussed what recursion is and how to use it, let's practice creating some recursive functions. On Tuesday we programmed the Fibonacci sequence using for loops. Now we are going to create a function that calculates the Fibonacci sequence recursively.
Start by doing the first exercise.
There are examples on this page that you can experiment with! Don't be afraid to copy the code into your program and play around with it. In the second exercise we will try to code the Fibonacci sequence. It might be a good idea to get out a scratch piece of paper and add up the first four or five numbers.
Don't be afraid to ask questions! We are always here to help.
Make sure that you try running the program after each excercise that you create! That way, if it doesn't work, it's a lot easier to figure out what's going on!
Take a screenshot of your output and please answer these questions on your webpage.