Recursion in C
Recursion in C
Recursion is the process which comes see the 2 ways to write the factorial
program.
into existence when a function calls a
copy of itself to work on a smaller
problem. Any function which calls itself ● Factorial Program using loop
is called a recursive function, and such ● Factorial Program using
function calls are called recursive calls. recursion
Recursion involves several numbers of
recursive calls. However, it is important Factorial Program using loop
to impose a termination condition of
recursion. Recursion code is shorter #include<stdio.h>
than iterative code however it is int main()
difficult to understand. {
int i,fact=1,number;
Recursion cannot be applied to all the printf("Enter a number: ");
problem, but it is more useful for the scanf("%d",&number);
tasks that can be defined in terms of for(i=1;i<=number;i++){
similar subtasks. For Example, fact=fact*i;
recursion may be applied to sorting, }
searching, and traversal problems. printf("Factorial of %d is:
%d",number,fact);
Generally, iterative solutions are more return 0;
efficient than recursion since function }
call is always overhead. Any problem
that can be solved recursively, can Output:
also be solved iteratively. However, Enter a number: 5
some problems are best suited to be Factorial of 5 is: 120
solved by the recursion, for example,
Fibonacci series, factorial finding, etc. Factorial Program using recursion
in C
Factorial Program in C
1. #include <stdio.h>
Factorial of n is the product of all 2. int fact (int);
positive descending integers. Factorial 3. int main()
of n is denoted by n!. 4. {
5. int n,f;
For example: 6. printf("Enter the number
5! = 5*4*3*2*1 = 120 whose factorial you want to
3! = 3*2*1 = 6 calculate?");
7. scanf("%d",&n);
Here, 5! is pronounced as "5 factorial", 8. f = fact(n);
it is also called "5 bang" or "5 shriek". 9. printf("factorial = %d",f);
10. }
The factorial is normally used in 11. int fact(int n)
Combinations and Permutations 12. {
(mathematics). 13. if (n==0)
14. {
There are many ways to write the 15. return 0;
factorial program in c language. Let's 16. }
17. else if ( n == 1) 1. if (test_for_base)
18. { 2. {
19. return 1; 3. return some_value;
20. } 4. }
21. else 5. else if (test_for_another_base)
22. { 6. {
23. return n*fact(n-1); 7. return some_another_value;
24. } 8. }
25. } 9. else
10. {
Output 11. // Statements;
Enter the number whose factorial you 12. recursive call;
want to calculate?5 13. }
factorial = 120
Fibonacci Series in C
We can understand the above In case of fibonacci series, next
program of the recursive method call number is the sum of previous two
by the figure given below: numbers for example 0, 1, 1, 2, 3, 5, 8,
13, 21 etc. The first two numbers of
fibonacci series are 0 and 1.
Output:
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;