Java Recursive process

Source: Internet
Author: User

Recursive two words as the name implies: Pass the past, return, so I simply call it to do have to borrow it.

The following example comes from C:

Public class Main {
public static void Main (string[] args) {
Fun (1);
}

Public static void fun (int n) {
System.out.printf ("1-lexe:%d \ n"); #1
if (n < 3)
Fun (n + 1);
System.out.printf ("2-lexe:%d \ n"); #2
                                }

}

The results of the output are as follows:

1-lexe:1
1-lexe:2
1-lexe:3
2-lexe:3
2-lexe:2
2-lexe:1

Process interpretation:

First, main () called the function Fun (1) , so fun (1) the value of parameter n is 1, so the print statement #1 output:1-lexe:1 .

Then, because n < 3, (level 2nd) of the Fun (n+1) is called. At this time n+1=2, so the print statement #1 output:1-lexe:2.

Then, because n < 3, (level 3rd) of the Fun (n+1) is called. At this time n+1=3, so the print statement #1 output:1-lexe:3.

because at this point, n=3, the IF statement is no longer executed.

The #2 statement is then executed because the value of n is 3, so the print statement #2 output: 2-lexe:3. ---------------------------This completes a "pass through"

The function call is now complete

Now the function needs to "return", back to the last call to the function, that is, where the n+1=2, so the print statement #2 output:2-lexe:2.

return to the place where the first call, N =1, so the print statement #2 output:2-lexe:1. ----------------------------- completed a "return"

In fact, his "return" of the entry point is the function of the call points, get the parameter values here, a first-level outward breakout on the out.

The following is a recursive flow of an operation: http://www.cnblogs.com/OldZhao/p/5062582.html

Java Recursive process

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.