M
M
meinhard2013-12-20 14:49:46
Java
meinhard, 2013-12-20 14:49:46

How does the recursive method work?

Please explain in detail step by step what happens at each step of this code
. I've been struggling for two hours already, I just can't understand the principle, it's only clear what happens up to the value = 1, and where it returns and what happens next - "dark forest".

class Factorial {

    int fact(int n) {
        int result;
        if (n == 1) {
            return 1;
        }
        result = fact(n - 1) * n;
        return result;
    }
}
class Recursion {

    public static void main(String args[]) {
        Factorial f = new Factorial();

        System.out.println("Факториал 3 равен " + f.fact(3));
    }
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
veontomo, 2013-12-20
@meinhard

The value is returned to the person who requested it.
For example, if you request f.fact(1), then the Factorial::fact method will immediately return 1.
For the f.fact(2) request, the call chain will be as follows:
first request Factorial::fact(2), which will return Factorial::fact (1) * 2.
In the response, there is again a Factorial::fact(1) query that returns 1. Thus, we get 2 * 1, i.e. 2.
The rest of the examples follow the same pattern:
f.fact(10) -> f.fact(9) * 10 -> f.fact(8) * 9 * 10 -> ... -> f.fact( 1) * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10.

S
sdevalex, 2013-12-20
@sdevalex

Do It

// ...
result = fact(n - 1) * n;
System.out.println(result);
// ...

It becomes clear what goes where.

S
swinntus, 2013-12-20
@swinntus

In fact, this method loops until n = 1, after which it starts multiplying first by 2, then by 3, and so on. until the value = n, after which the method returns the resulting product

A
afiskon, 2013-12-21
@afiskon

The method calls itself. What's incomprehensible here?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question