A function which calls itself is called as recursive function.
- Are slower in speed becuase of stack overhead.
- Should have recursive expression with terminating statement.
Program working steps
- First line is the comment, 2nd and 3rd line are preprocessor directives which holds definition of functions like clrscr(), printf(), scanf() etc.
- void main() is the funtion, where program execution starts.
- Declaration of variable number to store input number and fact to display the required result.
- clrscr() function to clear the screen like cls in windows and clear in linux.
- Next two statements takes the input from the user and stores the value into variable number.
- Line no.11 calls the factorial function by passing number variable to it. So the program control transfers to line no.15, where a block of code for calculating the factorial of a number is written.
- factorial function takes one argument from the caller function and stores the value into the variable n of integer data-type.
- First is the terminating condition if(n<2) then break recursive loop, else part contains recursive expression return n*factorial(n-1) which calls itself.
- Suppose the user enters 4 as a value then the factorial function will work like,
Fist the terminating condition
if(4<2) is false so it will execute else part
this statement calls the factorial function with(4-1)as a argument, so it will again start from first statement.
if(3<2) now the value of n is decrease by one, but still condition is false so it will execute else part.
3*factorial(3-1) This statement again calls itself.
This will keep repeating till terminating condition becomes true i.e. when n = 1. Then the function will return the calculated value using return f; statement.
A closer lookup of the recursive calls
- This calculated f value will be return back to calling functoin to line no.11, where value of fact will be 16.
- Next printf statement prints the quoted text, 'Factorial of given number is 16.'.
- getch() to wait input character to exit the program.
Recursive function should have exit condition to avoid stack overlfow.