Question:
Explain the concept of recursive thinking in computer science. Provide an example of a problem that can be solved using recursion and write a recursive function to solve it in Java.
Answer:
Recursive thinking in computer science involves solving problems by breaking them down into smaller, more manageable subproblems. This approach involves calling the same function within itself to work on these subproblems, eventually leading to a base case where the function stops calling itself and returns a final result.
Example problem: Write a recursive function to calculate the factorial of a given number n.
Java code:
```java
public class Factorial {
public static int calculateFactorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
} else {
return n * calculateFactorial(n - 1); // Recursive call to calculate factorial
}
}
public static void main(String[] args) {
int number = 5;
int factorial = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + factorial);
}
}
In this example, the calculateFactorial
function takes an integer n
as input and recursively calculates its factorial by calling itself with n-1
until it reaches the base case of n=0
. The final result is then returned.