Search Menu

Contents

Types of Recursion

page 3 of 3

Types of Recursion

Types of Recursion

Types of Recursion

Types of Recursion

A recursive function doesn't necessarily need to call itself. Some recursive functions work in pairs or even larger groups. For example, function A calls function B which calls function C which in turn calls function A.

A simple example of mutual recursion is a set of function to determine whether an integer is even or odd. How do we know if a number is even? Well, we know 0 is even. And we also know that if a number n is even, then n - 1 must be odd. How do we know if a number is odd? It's not even!


int is_even(unsigned int n)
{
	if (n==0) return 1;
	else return(is_odd(n-1));
}

int is_odd(unsigned int n)
{
	return (!iseven(n));
}

I told you recursion was powerful! Of course, this is just an illustration. The above situation isn't the best example of when we'd want to use recursion instead of iteration or a closed form solution. A more efficient set of function to determine whether an integer is even or odd would be the following:


int is_even(unsigned int n)
{
	if (n % 2 == 0) return 1;
	else return 0;
}

int is_odd(unsigned int n)
{
	if (n % 2 != 0) return 1;
	else return 0;
}