+ 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?
2 ответов
+ 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
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