Click here to Skip to main content
15,897,226 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How recursion works in c? explaination with detail example.
Posted
Comments
Jochen Arndt 29-Jan-13 5:35am    
Homework?
[no name] 29-Jan-13 6:15am    
Maybe someone knows whether the C compiler optimization for tail-recursion?

You'd better learn how to perform a simple Google search[^].
 
Share this answer
 
v2
Just the same way it does in any other programming language.

Since this smells heavily of your homework, I'll give you no code! But it's pretty simple:
Take a factorial as an example (it's not actually something you would implement with recursion becasu ethere are much better ways to work it out, but it is easy to explain and understand).

Factorial(N) = N * Factorial(N -1) while N > 1

So the definition of a Factorial uses a Foactorial to define itself - it refers to itself as part of it's definition. It uses recursion to define itself. That's why some dictionary definitions[^] of recursion consist of just the words: "see Recursion"

So when you write a function to calculate a factorial, you can write it as this:
C++
int Factorial(int N)

1) If N <= 1, return 1
2) return N * Factorial(N - 1)
 
Share this answer
 
C#
#include<stdio.h>
int fact(int);
int main(){
  int num,f;
  printf("\nEnter a number: ");
  scanf("%d",&num);
  f=fact(num);
  printf("\nFactorial of %d is: %d",num,f);
  return 0;
}

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




factorial is a best and simple example for recursion....
 
Share this answer
 
In C recursion is just like ordinary function calls.

1. When a function is called, the arguments, return address, and frame pointer are pushed on the stack.
2. In the called function, first the space for local variables is "pushed" on the stack.
3. if function returns something, put it in a certain register (depends on architecture, AFAIK)
4. undo step 2.
5. undo step 1.
So, with recursion steps 1 and 2 are performed a few times, then possibly 3 (maybe only once) and finally 4 and 5 are done (as many times as 1 and 2).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900