Recursion:
1. Call yourself;
2. There must be a condition that tends to terminate.
(Recommended tutorial: java course)
The following is a brief introduction to an example of finding factorial:
public class recursion { public static int fac(int n) { if(n == 1){ return 1; //终止条件 } return n * fac(n-1); //调用自身 } public static void main(String[] args) { System.out.println(fac(5)); } } // 运行结果: 120
The recursive process (first gradient )
#Second dimension: Method invocation requires memory to be allocated on the stack
The stack is first in, last out.
First call fac(5), then gradually call fac(4)... until the termination condition.
The process of pushing onto the stack is the process of passing.
As long as the termination condition return is encountered, the function ends and the value of fac(n) is gradually returned.
The process of popping out of the stack is the process of returning.
Related recommendations: Getting Started with Java
The above is the detailed content of What is recursion. For more information, please follow other related articles on the PHP Chinese website!