+ 2

Please Helpp

in the code: int factorial(int n) { if (n == 0) return 1; return n*factorial(n-1); } i think the code should return 1 always return 1.Since it will eventually be 1 but how is this returning the factorial???

2nd Jul 2020, 10:50 AM
Nazeefa Labiba
Nazeefa Labiba - avatar
2 Respostas
+ 19
Nazeefa Labiba Factorial function is an example of recursion. Recursion is happen when an function call itself again and again. And their must be an halting condition for recursion which is used to terminate the recursion. Here when you take an number like 5 then 5 is first check in if block so 5 is not equl to 0 so it goes out of if block and return 5*(factorial(5-1) which is 5*factorial(4). Now factorial(4) is called again this way in the end it will be like. 5*4*3*2*1=120 it will return 1 only when the number is equal to 0 so when n==0 it will return 1 else for every other number last return statement is called. This way it return the factorial of number. Here is detailed explanation present have an read. https://www.sololearn.com/learn/CPlusPlus/1641/?ref=app
2nd Jul 2020, 10:57 AM
GAWEN STEASY
GAWEN STEASY - avatar
+ 9
See again the code how its working. For example you entered 5 it will be calculate in reverse order upto when entered Number will be zero it will return 1 . You have to understood the concept of recursion
4th Jul 2020, 4:33 AM
A S Raghuvanshi
A S Raghuvanshi - avatar