Home / Questions / Write a Java program to demonstrate recursion.
Explanatory Question

Write a Java program to demonstrate recursion.

👁 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

Write a Java program to demonstrate recursion.

The following Java program calculates the factorial of 4 using recursion.

public class Mystery {

    public void run() {
        int result = compute(4);
        System.out.println(result);
    }

    public int compute(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n * compute(n - 1);
        }
    }

    public static void main(String[] args) {
        Mystery m1 = new Mystery();
        m1.run();
    }
}
Output: 24