简体   繁体   English

Java递归执行流程

[英]Java Recursion Flow of execution

public static void main(String[] args) {
    System.out.println(prod(1, 4));
}

public static int prod(int m, int n) {
    if (m == n) {
        return n;
    } else {
        System.out.println(n);
        int recurse = prod(m, n - 1);
        System.out.println(recurse);
        int result = n * recurse;
        return result;
    }
}

Struggling to understand the flow of execution here. 在这里努力了解执行流程。

within the if clause, when m =n, in the case 1=1, it returns n =1, but from here it goes straight to declaration of int recurse and then that same n becomes 2. I dont understand what happened. 在if子句中,当m = n时(在1 = 1的情况下)返回n = 1,但是从这里直接进行int递归的声明,然后该n变为2。我不知道发生了什么。

Your program will call prod() function recursively and store local variable in stack till m!=n . 您的程序将递归调用prod()函数,并将局部变量存储在堆栈中,直到m!=n为止。 Once m becomes equal to n, it will start executing remaining part of program stored in stack. 一旦m等于n,它将开始执行存储在堆栈中的程序的剩余部分。

For better understanding i am adding System.out.println() statement in your program. 为了更好地理解,我在您的程序中添加了System.out.println()语句。

public static void main(String[] args) {
    System.out.println("Final Output in Main "+prod(1, 4));
}

public static int prod(int m, int n) {
    if (m == n) {
        System.out.println("Return Result: "+n);
            return n;
    } else {
        System.out.println("Print : "+n);
            int recurse = prod(m, n - 1);
        System.out.println("Print Recurse: "+recurse);
            int result = n * recurse;
        System.out.println("Return Result: "+result);
            return result;
    }
}

Flow of program would be like 程序流程会像

Print : 4
Print : 3
Print : 2
Return Result: 1
Print Recurse: 1
Return Result: 2
Print Recurse: 2
Return Result: 6
Print Recurse: 6
Return Result: 24
Final Output in Main 24

If m is 1 and n is 4, this is what it does: 如果m为1且n为4,这就是它的作用:

  1. Print 4 列印4
  2. Call prod(1, n -1) 调用prod(1, n -1)
  3. Print 3 打印3
  4. Call prod(1, n -1) 调用prod(1, n -1)
  5. Print 2 列印2
  6. Call prod(1, n -1) 调用prod(1, n -1)
  7. Print 2 列印2
  8. Print 4 列印4
  9. Return 4 返回4
  10. Print 4 列印4
  11. Print 12 etc 打印12等

I think I got this right.. As it returns, it unwinds the stack. 我想我没错。.当它返回时,它使堆栈松开。 Even if I got the #10 and #11 steps wrong you should get the general idea. 即使我弄错了#10和#11步骤,您也应该了解总体思路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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