Home / Questions / Why is the compute() method recursive? return n * compute(n - 1);
Explanatory Question

Why is the compute() method recursive?

return n * compute(n - 1);
        

👁 0 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

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);
    }
}