Detailed explanation of recursion in java

Method Recursion in Java Method
Recursion
Recursion is an algorithm that is widely used in programming languages.
The form in which a method calls itself is called method recursion.

Forms of recursion
Direct recursion: The method calls itself.
Indirect recursion: methods call other methods, and other methods call back the method itself.

Precautions for method recursion
If the recursion is not terminated properly, a recursive infinite loop will occur, resulting in stack memory overflow.

Three elements of a recursive algorithm
Recursive formula
Recursive end point
The direction of recursion must go to the end point

public class Recursion01 {
    
    
    public static void main(String[] args) {
    
    
        T t = new T();
        t.test(4);
    }

}
class T {
    
    
    public void test(int n) {
    
    
        if(n > 2) {
    
    
            test(n-1);
        }
        System.out.println(n);
    }
}

insert image description here

The running results are as follows:
2
3
4

public class Recursion01 {
    
    
    public static void main(String[] args) {
    
    
        T t = new T();
        t.test(4);
    }
}
class T {
    
    
    public void test(int n) {
    
    
        if(n > 2) {
    
    
            test(n-1);
        }else {
    
    
            System.out.println(n);
        }
    }
}

insert image description here
Note the difference between Example 1 and Example 2. Example 1 is to execute the test method, and the current n will be printed. Example 2 is to make a judgment that it is less than or equal to 2 and print the current n.

recursive sum

public class diguiqiuhe {
    
    
    public static void main( String[] args ) {
    
    
        int num=5;
        int sum=getSum(num);
        System.out.println(sum);
    }

    private static int getSum( int num ) {
    
    
        if (num==1){
    
    
            return 1;
        }
        return  num+getSum(num-1);
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_45817985/article/details/130881247