Php recursion. I read php recursion on the Internet just now, and asked me again, telling me that recursion is called itself. Did not understand. I also read the Quita issue on Baidu. Actually, I know what is going on with the tower, but I still don't understand recursion. Hope that the ox people will give an easy-to-understand example...
Reply to discussion (solution)
Function f ($ n) {$ out =-1; if ($ n <0) echo "the input cannot be a negative number "; else if ($ n = 0 | $ n = 1) $ out = 1; else $ out = f ($ n-1) * $ n; return $ out ;} echo f (3 );
The most typical example is factorial.
Function f ($ n) {$ out =-1; if ($ n <0) echo "the input cannot be a negative number "; else if ($ n = 0 | $ n = 1) $ out = 1; else $ out = f ($ n-1) * $ n; return $ out ;} echo f (3 );
The best example is factorial... It seems that iq is not enough.
F (3) the parameter passed to f function for the first time is 3 to $ out = f ($ n-1) * $ n; and then changed $ out = f (3) = f (2) * 3; f (2) has not produced any results, so I called the f function again. this is f (2) the parameter is 2 and runs again to $ out = f ($ n-1) * $ n; it becomes $ out = f (2) = f (1) * 2; f (1) when this function is run, else if ($ n = 0 | $ n = 1) is run. Therefore, f (1) = 1; f (1) is known) returns the previous $ out = f (2) = f (1) * 2 = 1*1 = 1; $ out = f (2) = f (1) * 2 = 1*2; $ out = f (3) = f (2) * 3 = 2*3; the result is 6.