What is Recursion?


Problems

Problem : What does the following function do?


int mystery(int a, int b) 
{
	if (b==1) return a; 
	else return a + mystery(a, b-1); 
}
How would you categorize it?


Problem : Suppose we wrote a function to see if a tree node is part of a tree whose root has a specified name:


int root_named_x(tree_node_t *node, char* x)
{
	if (strcmp(node->name, x) == 0) return 1;
	else if (node->parent == NULL) return 0;
	else return root_named_x(node->parent, x);
}
How would you categorize this function?


Problem : Convert the following tail-recursive function into an iterative function:


int pow(int a, int b)
{
	if (b==1) return a;
	else return a * pow(a, b-1);
}


Problem : What category would the following function fit into? How many function calls will there be in total if the function is called with func(10)?


void func(int n)
{
	if (n!=1) {
		func(n-1);
		func(n-1);
	}
}


Problem : Continuing from the last problem, with a call func(10), how many function calls will there be in total with the following function?


void func(int n)
{
	if (n!=1) {
		func(n-1);
		func(n-1);
		func(n-1);
	}
}


Take a Study Break

SparkLife

Star Trek gets SEXY

Chris Pine and Zoe Saldana heat up the red carpet!

SparkLife

Are you afraid of relationships?

Auntie SparkNotes can help!

SparkLife

Wanna get JLaw's gorgeous glow?

Click here for simple, sexy makeup tricks!

SparkLife

Sexy starlet style

See every single look from the Met Gala!

SparkLife

Who'd be on your zombie-apocalypse crew?

We already dib'sed Genghis Khan.

Geek out!

The MindHut

Geeky Actors: Then and Now

Travel back in time!

The MindHut

How To Look Like J-Law...

When you don't look like J-Law.

The MindHut

Top 10 Predictions Sci-Fi Got WRONG

So wrong, they're WRONG.

The MindHut

The 15 Most Awesome Robots, Ever

These Robots Rock!

The MindHut

If You Like Game of Thrones...

...Then you'll LOVE these books!

The Book

Cover image

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps