开发者

Tracing order of execution in Java

I have a factorial code

class FactorialTest {

    public static void main(String args[]){
        System.out.println(factorial(10));
    }

    public static int factorial(int N){
        if (N <= 1) return 1;
        return N*factorial(N-1);
    }
}

It was traced using Trace, and this is the output:

Tracing order of execution in Java

Does that mean that recursion part always done first开发者_高级运维, and the multipication is later?


The recursion must be done first, since it is an argument to the multiplication. Before the recursion gets done, what would even be multiplied?

I don't think your Trace output tells you that, though. I'm answering only after reading the code.


It's possible to implement factorial using tail recursion, but in your code the multiplication follows the recursive call so a tail cail optimization cannot be applied.


Of course the recursive call must be evaluated first. You are multiplying two expressions, one of which is simply a value (N) the other is a recursive call. Without making the call and getting the result first, how would you expect to multiply that to N?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜