[Solved] Please give me an explanation of how this return value is determined [closed]


A function works like this:

The first line of code

public int foo (int n, int f)

is the function declaration with its visibility (public), its return data type (int), its name (foo) and its parameters (n of the type int and f of the type int).

What the visibility is, is not important for this question and I assume you know what an int is and what the name of the function is and how it is used. Parameters offer you a possibility to use values of outside the function, which is e.g. useful when you need to access information which you could/should not be able to receive from inside the function.

Next you get the function’s body beginning with the termination condition of when n is exactly 1, the function will simply return the current value of f to the calling function.

if (n == 1) {
    return f;
}

If n is not 1, then a recursive call is made in the function. This means, that the function will be called and the result of the call will be returned to this point of execution when the function is done. This happens before the return statement is executed. When the function is done, the return statement is executed and the result of the in-function call will be returned to the caller of the function itself.

How it is executed in your example:

1st call: foo (5, 1) -> n is not 1 -> return foo (4, 6)

2nd call: foo (4, 6) -> n is not 1 -> return foo (3, 10)

3rd call: foo (3, 10) -> n is not 1 -> return foo (2, 13)

4th call: foo (2, 13) -> n is not 1 -> return foo (1, 15)

5th call: foo (1, 15) -> n is 1 -> return 15 to call 4

4th call: return 15 to call 3

3rd call: return 15 to call 2

2nd call: return 15 to call 1

1st call: return 15 to caller

solved Please give me an explanation of how this return value is determined [closed]