- Recursive function (returns number) int function(int n);
- if-else statement
- Static variable
How program works
- User enters a number which stores in variable 'num'
- Then number passes as argument in function call
- A static variable is used to check that how many times function is called
- When base case becomes true if(statement) then function returns result to main
As a beginner some questions can be raised regarding code.
Why static variable is used instead of a simple int variable?
- The property of static variable is that it is initialized when program runs first time
- Its value increments on every call and it is not initializing again and again
- if we do not use static keyword then variable ' int i=1;' will be initialize again and again and its value will not be correct at the end infact it will remain 1 always.
- So that is why static in has been used to count the number of calls
To provide more readable view here is image view of code:
Sample Input Output
To learn fast change the code and examine output.