✏️ Explanatory Question

Why is the compute() method recursive?

return n * compute(n - 1);
        

👁 12 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Why is the compute() method recursive?

The compute() method is recursive because it calls itself inside its own body.

return n * compute(n - 1);

Here, compute(n - 1) is a recursive call because the method compute() is invoking itself again with a smaller value.



public class RecursionExample {

    public static int compute(int n) {

        // Base case
        if (n == 0) {
            return 1;
        }

        // Recursive case
        return n * compute(n - 1);
    }

    public static void main(String[] args) {
        int result = compute(5);
        System.out.println("Result: " + result);
    }
}