Di Posting Oleh : Simple Learning
Kategori : factorial program in c++ using recursive function simple recursion program in c++
Write a program to find the Factorial using recursive function. User will enter a number and program should display result.
Concept used:
Concept used:
- 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
c++ code
As a beginner some questions can be raised regarding code.
Why static variable is used instead of a simple int variable?
To provide more readable view here is image view of code:
Sample Input Output
Recommended:
To learn fast change the code and examine output.
#include<iostream> |
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
Recommended:
To learn fast change the code and examine output.
0 Response to "C++ program to find factorial using recursion"
Post a Comment