Php recursion.

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.