Recursive functions are those functions which call themselves directly or indirectly. If a function calls itself again, that will make a repetition and will work like a loop. In order to make a logical end to the repetitive call, we have to add an expression to break the flow of recursive call. Consider the program of factorial which finds the factorial of the input number. It can be written using recursive function as given below.
Recursive Function Example in C
- #include<stdio.h>
- int factorial(int n);
- void main()
- {
- int num;
- int fact;
- printf("Enter the number:");
- scanf("%d", &num);
- fact = factorial(num);
- printf("Factorial of %d is %d", num, fact);
- }
- int factorial(int n)
- {
- if(n == 1)
- {
- return 1;
- }
- else
- {
- return (n * factorial(n -1));
- }
- }
Let’s take the input number as 3. Then the factorial function is called with value 3. Inside the function it will check whether 3 is equal to 1 and then execute the
'else'
statements. The return statement will look like 'return (3 * factorial (2))'
. Now 'factorial(2)'
will again enter the 'else'
statement as the 'if'
condition fails. This time it will return '(2 * factorial(1))'
. Now 'factorial(1)'
returns value 1 which will result the output (3 * (2 * 1))
i.e. 6.
One thing to remember while using recursive function is that if you omit the check expression or if the expression never be satisfied, it will cause an infinite loop. Recursion is another way to simulate loop and can be replaced by a simple loop statement (also called iteration)
No comments:
Post a Comment