help!! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

help!!

how this function int factorial(int n) { if (n==1) { return 1; } else { return n * factorial(n-1); } } retuns a next lower n when we have just type n-1 in calling a retun?

13th Mar 2017, 11:17 AM
Matej Čalić
Matej Čalić - avatar
2 Answers
+ 18
this is the concept of recursion where a function is calling it self it like loop let us take n=5 fact(5) is called and returns (5*fact(5-1)) fact(5-1) is called i.e.,fact(4) returns (4*fact(4-1)) fact(4-1) is called i.e.,fact(3) returns (3*fact(3-1)) fact(3-1) is called i.e.,fact(2) returns (2*fact(2-1)) fact(2-1) is called i.e.,fact(1) returns 1 so fact(2) return(2*1) i.e., return 2 fact(3) return(3*2) i.e., return 6 fact(4) return(4*6) i.e., return 24 fact(5) return(5*24) i.e., return 120 here is the output factorial of 5= 120
13th Mar 2017, 12:16 PM
Mansi Dagla
Mansi Dagla - avatar
0
Recursion keeps on calling function until the base condition is met. On reaching base condition, function travels back. Let's us examine the execution factorial (5) = 5 * factorial (4) = 5 * 24 = 120 factorial (4) = 4 * factorial (3) = 4 * 6 = 24 factorial (3) = 3 * factorial (2) = 3 * 2 = 6 factorial (2) = 2 * factorial (1) = 2 * 1 = 2 factorial (1) = 1
13th Mar 2017, 12:23 PM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar