Recursion Flashcards

1
Q

What is “recursion?”

A

calling a function on itself

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a “factorial”

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what is the “base case?”

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a “termination condition?”

A

a statement that will cancel recursion in the event of bad input or other potential error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to build your recursive case (the code that will be repeated)

A

ensure that the arguments you use for the recursion will lead to your base case

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

factorial example (at the bottom show how the factorial runs through the base case)

A

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)...
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

where is the data stored while you are running a function?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

another factorial example

A
// 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly