Explanatory Question
Write a Java program to demonstrate recursion.
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.
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();
}
}
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.