Rate this:
See more:
How recursion works in c? explaination with detail example.
Posted 29-Jan-13 0:31am
Jochen Arndt at 29-Jan-13 5:35am

Homework?
Dmitry_Novikov81 at 29-Jan-13 6:15am

Maybe someone knows whether the C compiler optimization for tail-recursion?

Rate this:

## Solution 1

You'd better learn how to perform a simple Google search[^].
v2
Rate this:

## Solution 2

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:
`int Factorial(int N)`
1) If N <= 1, return 1
2) return N * Factorial(N - 1)
Rate this:

## Solution 3

```#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....
Rate this:

## Solution 4

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).