×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
• Talk With Other Members
• Be Notified Of Responses
• Keyword Search
Favorite Forums
• Automated Signatures
• Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

#### Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

# C FAQ

 What is recursion, and Can I see an example? by mbaranski faq205-484 Posted: 12 Feb 01 OK, you have to think about like 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 factorialThink 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 have4 * 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. Back to C FAQ Index Back to C Forum

Close Box

# Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

• Talk To Other Members
• Notification Of Responses To Questions
• Favorite Forums One Click Access
• Keyword Search Of All Posts, And More...

Register now while it's still free!