12,622,913 members (30,729 online)

Email

Password

Sign in using

How recursion works in c? explaination with detail example.

only parvej253

Comments

Homework?

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

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

So when you write a function to calculate a factorial, you can write it as this:

2) return N * Factorial(N - 1)

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 12) return N * Factorial(N - 1)

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

In

1. When a function is called, the arguments, return address, and frame pointer are pushed on the

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

`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

3. if

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)

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