Recursive method refers to the process of invoking itself within a method, recursion must have an end condition, otherwise it will fall into the state of infinite recursion, can never end the call, followed by a simplest example to reflect the method recursion, using recursive algorithm to calculate the sum of natural numbers:
public class Example18 {<span style= "white-space:pre" ></span>public static void Main (string[] args) {< Span style= "White-space:pre" ></span>int sum = getsum (4); //Call the recursive method to get 1~4 and <span style= "White-space:pre" ; </span>system.out.println ("sum =" + sum); Print result <span style= "White-space:pre" ></span>}<span style= "White-space:pre" ></span>// The following method uses the recursive implementation to find the 1~n and <span style= "White-space:pre" ></span>public static int getsum (int n) {<span style= " White-space:pre "></span>if (n = = 1) {<span style=" white-space:pre "></span>//meet condition, recursive end <span Style= "White-space:pre" ></span>return 1;<span style= "White-space:pre" ></span>}<span style = "White-space:pre" ></span><span style= "White-space:pre" ></span>return n+getSum (n-1);< Span style= "White-space:pre" ></SPAN>}}
The result is: sum = ten
I am a beginner, I used to dictate the explanation of the above code, such as wrong, please put forward, I directly from the summation of the method to explain it
if (n = = 1) This is the condition if n equals 1 returns 1
<pre name= "code" class= "Java" >return n+getsum (n-1);
First recursion 4+ (4-1) Second recursion 4+ (3-1) Second recursion 4+ (2-1) fourth time meet condition direct return 1 that n=4 has not changed, then add 1+2+3+4=10.
Another example of factorial, the code is as follows:
public class Example018 {<span style= "white-space:pre" ></span>static int multiply (int n) {<span Style= "White-space:pre" ></span>if (n==1) {<span style= "white-space:pre" ></span>return N; <span style= "White-space:pre" ></span>}<span style= "White-space:pre" ></span>return N Multiply (n-1); } <span style= "White-space:pre" ></span>public static void Main (string[] args) {<span style= "wh Ite-space:pre "></span>system.out.println (Multiply (3)); } }
This code needs to be multiplied
if (n==1)
If equals 1, returns 1.
Return n*multiply (n-1);
N=3 (3-2) * (2-1) * *
Read the message you don't know or add me Penguin 654249738
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java_se basic--18. Recursion of the method