Search code examples
javarecursionfactorial

Factorial Program printing out the recursion


I have a Factorial Program written down. I have the whole program completed and it runs without any problems. However, I want the output to look like this

Begin Factorial Program. . . 
Provide number and the factorial will be computed: 4
4! is . . . 
In f(4) and calling f(3) . . . 
In f(3) and calling f(2) . . . 
In f(2) and calling f(1) . . . 
In f(1) and calling f(0) . . . 
  In f(0) and computing f(0). Returning 1
f(1) is 1 * 1 which equals 1. Returning 
f(2) is 2 * 1 which equals 2. Returning 2
f(3) is 3 * 2 which equals 6. Returning 6
f(4) is 4 * 6 which equals 24. Returning 24
4! = 24

How would I get.

f(1) is 1 * 1 which equals 1. Returning 
f(2) is 2 * 1 which equals 2. Returning 2
f(3) is 3 * 2 which equals 6. Returning 6
f(4) is 4 * 6 which equals 24. Returning 24

print out in my method

This is the method I have

public static int factorial(int num) {
    if (num == 0) {
        System.out.println("In f(" + num + ") and computing f(" + num
                + "). Returning " + 1);
        return 1;
    } else {
        System.out.println("In f(" + num + ") and calling f(" + (num - 1)
                + ") . . .");


        return num * factorial(num - 1);
    }

which prints out

4! is . . .
In f(4) and calling f(3) . . .
In f(3) and calling f(2) . . .
In f(2) and calling f(1) . . .
In f(1) and calling f(0) . . .
In f(0) and computing f(0). Returning 1
4! = 24

Solution

  • Something like this should do the trick:

    public static int factorial(int num) {
        if (num == 0) {
            System.out.println("In f(0) and computing f(0). Returning 1");
            return 1;
        }
    
        System.out.printf("In f(%d) and calling f(%d) . . .%n", num,
                    num - 1);  // #1
    
        int factorial = factorial(num - 1);
        int result = num * factorial;
    
        System.out.printf(
            "f(%1$d) is %1$d * %2$d which equals %3$d. Returning %3$d%n",
                num, factorial, result);  // #2
    
        return result;
    }
    
    In f(4) and calling f(3) . . .
    In f(3) and calling f(2) . . .
    In f(2) and calling f(1) . . .
    In f(1) and calling f(0) . . .
    In f(0) and computing f(0). Returning 1
    f(1) is 1 * 1 which equals 1. Returning 1
    f(2) is 2 * 1 which equals 2. Returning 2
    f(3) is 3 * 2 which equals 6. Returning 6
    f(4) is 4 * 6 which equals 24. Returning 24
    24
    

    Notice how the factorial recursive call is sandwiched between the two print statements (we do this by storing it in a new variable as opposed to using its result in-line). As a result, all of the first print statements (#1) are executed before any of the second ones (#2), resulting in the desired format.

    Also, in cases like this, printf makes much more sense and makes things a little easier to read/develop.