• admin@embedclogic.com

Recursive function in C

Recursion is a process in which a defined function calls itself as long as the condition is correct, such functions are called recursive.

For e.g :

You can see factorial of n calls itself again with different input.so it is recursive.

Syntax

Flow of Recursive function
Recursion flow Diagram

Example

Program to find the factorial of any number using the recursive algorithm.

You can see in above example, let’s take a number 5

Step1:

factorial_result=factorial(5); //function Calling

factorial(5) jumps into its definition first time from its main with input 5.

Step2:

factorial(5-1) calls its definition first time from its own definition with input 4.

fact=1 x 5 x factorial(5-1);

Step3:

factorial(4-1) calls its definition second time from its own definition with input 3.

fact=1 x 5 x 4 x factorial(4-1);

Step4:

factorial(3-1) calls its definition third time from its own definition with input 2.

fact=1 x 5 x 4 x 3 x factorial(3-1);

Step5:

factorial(2-1) calls its definition second time from its own definition with input 1.

fact=1 x 5 x 4 x 3 x 2 x factorial(2-1);

Step6:

factorial(1)satisfy the first condition (input==1) so its return 1 to calling function i.e factorial(1).

fact=1 x 5 x 4 x 3 x 2 x 1;

Step7:

output (value stored in fact) returns from factorial function and save into facorial_result.

facorial_result=120;

So you can see that from step2 to step 5 everytime factorial(input) function calls itself from its definition.So factorial() function is recursive.