Recursion Flashcards
What is “recursion?”
calling a function on itself
What is a “factorial”
to take a factorial of a number, you multiply that number by each number between itself and one. So the factorial of 5 is equal to 5 * 4 * 3 * 2 * 1, or 120.
what is the “base case?”
this is a statement, usually within a conditional clause like if, that stops the recursion. If you don’t have a base case, the recursion will go on infinitely and your program will crash
What is a “termination condition?”
a statement that will cancel recursion in the event of bad input or other potential error.
How to build your recursive case (the code that will be repeated)
ensure that the arguments you use for the recursion will lead to your base case
factorial example (at the bottom show how the factorial runs through the base case)
function factorial(n) {
// termination condition if(n 0){ return n * factorial(n - 1); }; }
//show how the factorial runs: return n * (n-1) * (n-1-1) * (n-1-1-1)...
where is the data stored while you are running a function?
When you run a program, the data that is produced within that program (variables, function calls, etc.) are stored in the stack, which you can think of as a temporary storage device for the computer.
Every time a function is called within a program, the returned value of that function is stored in the stack.
another factorial example
// Create an empty array called "stack" var stack = []; // Here is our recursive function function power(base, exponent) { // Base case if ( exponent === 0 ) { return 1; } // Recursive case else { stack[exponent - 1] = base * power(base, exponent - 1); return stack[exponent - 1]; } }
//show how the factorial runs //base * base * base (through the number of times it takes for exponent to