All Flashcards
What are the differences between recursion and iteration?
Recursion: Uses function calls, can be more readable for some problems, may use more memory. Iteration: Uses loops, generally faster, uses less memory.
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");
olleh