book-notes

Chapter 3 - Recursion

Base case and the recursive case

function countdown(num) {
	console.log(num)
	if (num <= 1) { // base case
		return;
	} else { // recursive case
		countdown(num - 1);
	}
}

countdown(3) // 3, 2, 1

The stack

The call stack

Call stack example

function greet(name) {
	console.log("hello, " + name);
	greet2(name);
	console.log("getting ready to say bye");
	bye();
}

function greet2(name) {
	console.log("how are you " + name);
}

function bye() {
	console.log("bye");
}

greet("maggie");

The call stack with recursion

# iterative
def look_for_key(main_box):
	pile = main_box.make_a_pile_to_look_through()
	while pile is not empty:
		box = pile.grab_a_box()
		for item in box:
			if item.is_a_box():
				pile.append(item)
			elif item.is_a_key():
				print "found the key!"

# recursive
def look_for_key(box):
	for item in box:
		if item.is_a_box():
			look_for_key(item)
		elif item.is_a_key():
			print "found the key!"

Recap

Things we should do from Chapter 3

Neet codes