-8

I understand everything this method does up until m=1 and n=1. What happens after if() when m=1 and n=1 is problematic.

public class exc {

    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 {
            int recurse = prod(m, n - 1);                       

            int result = n * recurse;       // how n gets its value here?
            return result;

        }
    }
}
  1. What is the value of recurse? I mean how prod yields only one integer? (since it has two integers)

  2. In if, when m=1 and n=1 return value is 1 so why the program doesn't terminate at there? And instead it terminates after "return result;" in else?

  3. After m=1 and n=1, n is 2 (in recurse) ; how is n set to 2? Is it because 2 is still in memory and had to be dealt with?

I checked this page

I also used println after different lines to see the out put, but that didn't help either. I also used a debugger.

Community
  • 1
  • 1
Tahmoores
  • 1
  • 4

1 Answers1

1

Your program return the factorial when m = 1. Take this example: (m=1, n=4)

4 != 1 -> so you call recursively prod(1, 3) 
    3 != 1 -> so you call recursively prod(1, 2)
        2 != 1 -> so you call recursively prod(1, 1)
            1 == 1 -> you return 1 to the last call
        In this call, recurse = 1 and n = 2 so you return 2 to the upper call
    Here, recurse = 2, n = 3, so you return 6 to the upper call
Here, recurse = 6, n = 4, so you return 24 to the upper call

END OF FUNCTION, result is 24 which is 4!

Every time you are calling the function prod recursively, the current function prodA is paused (saving the values of its variables in memory) to execute the new function prodB until prodB returns something to prodA. Then A continues to execute itself (loading back its values from memory)

L01c
  • 1,033
  • 10
  • 19