Home > Java > Javagetting Started > What is recursion

What is recursion

王林
Release: 2020-09-30 15:57:32
forward
1991 people have browsed it

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
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template