Home > Java > JavaBase > How to recurse in java

How to recurse in java

angryTom
Release: 2019-11-14 14:50:13
Original
4866 people have browsed it

How to recurse in java

How to recurse in java

The essence of recursion: The programming technique of calling the program itself is called recursion.

Recursion as an algorithm is widely used in programming languages. A process or function has a method of directly or indirectly calling itself in its definition or description. It usually transforms a large and complex problem into a smaller problem similar to the original problem to solve. The recursive strategy only A small number of programs are needed to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of program code. The power of recursion lies in defining infinite collections of objects with finite statements.

Three conditions for recursion

a) Boundary condition

b) Recursive forward section

c) Recursive return section

When the boundary conditions are not met, the recursion advances; when the boundary conditions are met, the recursion returns.

The following is explained through two example programs:

Use Java code to find the factorial of 5. (Factorial of 5 = 5*4*3*2*1)

/** 
 * 计算5的阶乘(result = 5*4*3*2*1) 
 */  
public class Test01 {  
    public static void main(String[] args) {  
        System.out.println(f(5));  
    }  
      
    public static int f(int n) {  
        if (1 == n)   
            return 1;  
        else   
            return n*f(n-1);  
    }  
}
Copy after login

In this question, the analysis is based on the three conditions of recursion:

(1) Boundary conditions: factorial, multiplication When it reaches the last number, that is, 1, it returns 1 and the program is executed to the end;

(2) Recursive forward section: When the current parameter is not equal to 1, continue to call itself;

( 3) Recursive return segment: Start multiplying from the largest number. If the current parameter is 5, then it is 5*4, that is, 5*(5-1), that is, n*(n-1)

php Chinese Internet, a large number of free Java introductory tutorials, welcome to learn online!

The above is the detailed content of How to recurse in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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