简体   繁体   中英

Recursive Method Prints 4 Times

So I am working on learning how to utilize recursion through Java. I have written a simple program that adds all the numbers between 1 and n and it looks to do it's job. Where I get confused is the print statement, it prints 4 times (for each result of each smaller part of the solution) and I am confused how it reaches the print statement if the method is called again and the conditions aren't yet satisfied. I understand this can be circumvented by creating an int variable in the main method and having the return be assigned to it.

public static void main(String[] args) {

    int sum = recursiveCall(5);
}

public static int recursiveCall(int num) {

    int sum = 0;

    if(num == 1) {

        sum = 1;
        System.out.println(sum);
        return sum;
    }
    else {

        sum = recursiveCall(num - 1) + num;
    }

    // Notice it prints out all results of sum, not just the final value.
    System.out.println(sum);

    return sum;
}

Let me explain why this happens.

Your second print statement prints all the sum values except for when n = 1. When n = 1 the first print statement will print out the value

Think about this this way: Every non-void method call will return. If it does not return, it will continue executing until a return statement is reached.

You say that the second print statement should print only the last sum value. But you see, there are only two places that the method can return - in the if (num == 1) statement, or at the end of the method. The former location is reached only once when n is 1, which means that the other four times the method will return through the return statement at the end. To reach the return statement at the end, the second print must be executed. This means that the second print statement must be executed four times!

Use a debugger to step through the code step by step. This is the easiest to understand what actually happens.

I've drawn a sequence diagram, hope this can explain the recursion procedure.

There is a retrospective procedure for recursion, the next command will be pushed into the call stack before the recursion method is called. So we can simply say System.out.println will be pushed to call stack before recursiveCall , then after the recursiveCall returned the main process will continue with the top command on the stack, that is System.out.println .

递归过程

It is because of the second print statement below the else. On execution the recursive function is called and it doesn't reach the print statement at the bottom. But after n=1 ie the if condition is executed then it return to the function recursive(2-1) and go to the down and return sum (also the print) and return the value of sum to the place where recursive(3-1) is called and so on.. . That is where it prints each sum.

A Code which prints only the final sum is give below.Print is included in the main to print final answer only I hope this will help.

public class add {

    public static void main(String[] args) {

        int sum = recursiveCall(5);
        System.out.println(sum); // this will print 15
    }

    public static int recursiveCall(int num) {

        int sum = 0;

        if(num == 1) {

            sum = 1;
            //System.out.println(sum); this will print 1
            return sum;
        }
        else {

            sum = recursiveCall(num - 1) + num;
        }
        // System.out.println(sum); //this is the reason for each sum.
        return sum;

    }

}

When the recursion is stack is full, then it starts emptying itself from the tail. This is the reason your print statement below the if statements starts to get executed. Note: Recursion process will return its value where its called, so if conditions arent satisfied so it will return to that point, but the whole recursion process will keep on continuing until the stack is emptied. Whatever i said is what is called the Tail Recursion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM