Question

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.

Était-ce utile?

La solution

Your program will call prod() function recursively and store local variable in stack till m!=n. Once m becomes equal to n, it will start executing remaining part of program stored in stack.

For better understanding i am adding System.out.println() statement in your program.

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

Autres conseils

If m is 1 and n is 4, this is what it does:

  1. Print 4
  2. Call prod(1, n -1)
  3. Print 3
  4. Call prod(1, n -1)
  5. Print 2
  6. Call prod(1, n -1)
  7. Print 2
  8. Print 4
  9. Return 4
  10. Print 4
  11. Print 12 etc

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top