0

This is the following code I had for a recursion question

Is anyone able to run me through how the output is 24?

To prove how confused I am, I thought the output would have been 6, 12, 20 ,1

package Examples;

public class QuestionDemo {

public static void main(String[] args) {

    System.out.println(recCall(2));
}

public static int recCall(int num) {

    if (num == 5) {
        return 1;
    } else {
        return num * recCall(++num);
    }

}
}

5 Answers5

2

You have 4 recursive calls first one when you call recCall(2) then recCall(3), recCall(4) and recCall(5) recCall(5) returns 1 recCall(4) returns 4*1 recCall(3) returns 3*4*1 recCall(2) returns 2*3*4*1 = 24

DionizB
  • 1,487
  • 2
  • 10
  • 20
2

recCall(int num):

recall(2)
    |       | 
   2 *    recall(3)
              |       |
              3 *  recall(4)
                      |         |
                      4 *    recall(5)
                                |
                                1           



recall(2) = 24
            |       |
            2 *   12 = 24
                    |      |
                    3 *    4 = 12
                           |       |
                           4 *     1 = 4
                                   |
                                   1                                                 
Mustafa Çil
  • 766
  • 8
  • 15
1

This recursion takes a bottom-up approach. First going deepest to find the value of the base case, before you can get the value of other recursive calls.

This is why you're getting output = 24:

                                       _
                                      /|\ 
                                     / | \
recCall(4) = 4 * recCall(5) = 4  +  /  |  \ // recCall(5) is your base case.
recCall(3) = 3 * recCall(4) = 12 +     |
-----------------------------------    |
recCall(2) = 2 * recCall(3) = 24       | // This was your first call to the recursive function.

You're not traversing through values, but rather adding them all up.

Santiago Varela
  • 2,199
  • 16
  • 22
1

Its because you are using the recCall(++num), and you are using pre-increment operator which increases value before calling the method.

Please read how ++ pre increment works in java :- How do the post increment (i++) and pre increment (++i) operators work in Java?

So your recursive calls will look like below

 f(2)= 2*f(3)=2*12 = 24.
        f(3)=3*f(4)= 3*4=12
            f(4)=4*f(5) = 4*1
                f(5)= 1

hence it returns 24.

Community
  • 1
  • 1
Amit
  • 30,756
  • 6
  • 57
  • 88
0

Yes, if you try to move recall(++num) and put the new number which is ++num so result will be = 2 * 3 * 4 and in 5 it will return 1, so 2 * 3 * 4* 1.

Santiago Varela
  • 2,199
  • 16
  • 22