Home  >  Article  >  Java  >  What is recursion

What is recursion

王林
王林forward
2020-09-29 15:58:451925browse

What is recursion

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 )

What is recursion

#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.

What is recursion

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.

What is recursion

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete