It prevents infinite loops by providing a stopping condition for the recursive calls.
Flip to see [answer/question]
Flip to see [answer/question]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Flip
Revise later
SpaceTo flip
If confident
All Flashcards
Why is the base case important in recursion?
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 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));