12,622,913 members (30,729 online)
Rate this:
Please Sign up or sign in to vote.
See more:
How recursion works in c? explaination with detail example.
Posted 29-Jan-13 0:31am
Comments
Jochen Arndt 29-Jan-13 5:35am

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

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

## 4 solutions

Rate this:
Please Sign up or sign in to vote.

## Solution 1

You'd better learn how to perform a simple Google search[^].
v2
Rate this:
Please Sign up or sign in to vote.

## 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:
Please Sign up or sign in to vote.

## 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:
Please Sign up or sign in to vote.

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

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

Top Experts
Last 24hrsThis month
 OriginalGriff 235 John Simmons / outlaw programmer 199 ppolymorphe 125 Arthur V. Ratz 85 Mohtshm Zubair 50
 OriginalGriff 922 ppolymorphe 444 CPallini 293 John Simmons / outlaw programmer 289 Richard MacCutchan 232

Advertise | Privacy | Mobile
Web02 | 2.8.161128.1 | Last Updated 29 Jan 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100