Saved Bookmarks
| 1. |
The factorial of a number, say N is the product of first N natural numbers. Thus, factorial of 5 can be obtained by taking the product of 5 and factorial of 4. Similarly factorial of 4 be found out by taking the product of 4 and factorial of 3. At last the factorial of 1 is 1 itself. Which technique is applicable to find the factorial of a number in this fashion? Write a C++ function to implement this technique. Also explain the working of the function by giving the number 5 as input. |
|
Answer» A function calls itself is known as recursion. #include<iostream> using namespace std; int fac(int); int main() { int n; cout<<“enter a number”; cin>>n; cout<<fac(n); } int fac(int n) { if (n == 1) return (1); else return (n × fac(n – 1)); } The working of this program is as follows If the value of n is 5 then it calls the function as fa. The function returns value 5 × fac(4), That means this function calls the function again and returns 5 ×4 × fac(3). This process continues until the value n = 1. So the result is 5 × 4 × 3 × 2 × 1 = 120. |
|