It prevents infinite loops by providing a stopping condition for the recursive calls.
What happens in the call stack during recursion?
Each recursive call adds a new frame to the stack, storing parameters and return addresses. When a base case is hit, frames are popped off the stack as values are returned.
What is the trade-off between recursion and iteration?
Recursion can be simpler to read but may be slower and use more memory due to the call stack.
What is the role of parameters in recursive calls?
Parameters change with each recursive call, guiding the problem towards the base case.
How does recursion simplify problem-solving?
By breaking down a problem into smaller, self-similar subproblems.
What is the relationship between recursive calls and the base case?
Recursive calls move the problem closer to the base case, which provides a direct solution and stops further recursion.
What happens if a recursive method has no base case?
The method will call itself indefinitely, leading to a stack overflow error.
What is Recursion?
A way to simplify problems by having a subproblem that calls itself repeatedly.
What is a Base Case?
The condition that stops the recursive calls and returns a value.
What is a Recursive Call?
When a method calls itself, either with the same or different parameters.
What is a Call Stack?
A data structure that keeps track of active subroutines (methods) in a computer program.
What does this code output?
```java
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
System.out.println(factorial(3));
```
6
What does this code output?
```java
public static int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1);
}
}
System.out.println(sum(4));
```
10
Identify the error in the following code:
```java
public static void recurse() {
System.out.println("Hello");
recurse();
}
```
Missing base case, will cause a stack overflow.
What does this code output?
```java
public static int mystery(int a, int b) {
if (b == 0) {
return 0;
} else {
return a + mystery(a, b - 1);
}
}
System.out.println(mystery(2, 3));
```
6
What does this code output?
```java
public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
System.out.println(fibonacci(4));
```
3
What does this code output?
```java
public static void printReverse(String str) {
if (str.length() == 0) {
return;
} else {
printReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
printReverse("hello");
```