Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MDTKINDIA What is a recursive function? 1

Status
Not open for further replies.

Spannerman

Programmer
Dec 31, 2000
26
0
0
GB
Thanks for your reply MDTKINDIA what is a recursive function????
 
OK, you have to think about this:

let's think about n factorial, or n!:

1. Define a base case, or for our example:

if n = 0, n! = 1;

2. Define a recursive case:
if n > 0, n! = n * (n - 1)!
or, n factorial equals n times n-1 factorial

Think about this, we'll do an example:

take 4, 4!, using our recursive steps, is:
4! = 4 * 3!
4 * 3! = 4 * 3 * 2!
4 * 3 * 2! = 4 * 3 * 2 * 1!
4 * 3 * 2 * 1! = 4 * 3 * 2 * 1 * 0!
and, since 0! = 1, we have
4 * 3 * 2 * 1 * 1, or 4 * 3 * 2 * 1, which is the definition of factorial. In c, you would write this as:

int factorial (int n){
if (n == 0)
return 1;
else
return (n * factorial(n-1));
}

This will use the stack, and call itself until we reach the base case. The base case is very important, you must ensure that you will reach the base case. In the previous example, I know we won't be stuck in an infinite loop because each time we call the function we are decrementing n.

Good Luck, and if you need any more help, just post. I'm also putting this in the faq section. As always, I hope that helped!

Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top