Sunday, March 6, 2016

Recursive Functions

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

  1. #include<stdio.h>
  2. int factorial(int n);
  3.  
  4. void main()
  5. {
  6. int num;
  7. int fact;
  8. printf("Enter the number:");
  9. scanf("%d", &num);
  10.  
  11. fact = factorial(num);
  12. printf("Factorial of %d is %d", num, fact);
  13. }
  14.  
  15. int factorial(int n)
  16. {
  17. if(n == 1)
  18. {
  19. return 1;
  20. }
  21. else
  22. {
  23. return (n * factorial(n -1));
  24. }
  25. }
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: