Today touched a bit of recursion, the beginning of the time do not know what the meaning, just follow the answer code copied down, you can achieve their own purposes, on the Internet to see the feeling is not difficult to understand
But honestly, if you want to use it well, it's not a simple thing.
First look at a piece of code to find the factorial of a number
Public classQQQ {//calculates the factorial of a number Private Static intFactinta) {//the factorial of 1 would have been 1, and it would return directly . if(a==1) { returnA; } Else { return(A * fact (A-1)); } } Public Static voidMain (string[] args) {System.out.println (Fact (6)); }}
Recursion to a large extent similar to the loop, but not the loop, recursion is there to go back, the loop is to go back, in many cases recursion can be the code is simpler, but also easier to understand (this is really not found ...),
Look at this picture again.
This is the process diagram for calculating the factorial of a number using a recursive algorithm.
Principle is
Factorial ==6 of 6 times the factorial of 5
Factorial ==5 of 5 times the factorial of 4
Factorial ==4 of 4 times the factorial of 3
Factorial ==3 of 3 times the factorial of 2
Factorial ==2 of 2 times the factorial of 1
Factorial ==1 of 1
And then there's this thing in turn:
The factorial ==6 of 6 times 5 times 4 times 3 times 2 times 1 ...
So the factorial of 6 comes out.
Simple data collation, recursive algorithm