All Flashcards
What are the differences between recursion and iteration?
Recursion: Solves problems by calling itself | Iteration: Solves problems by repeating a block of code. Recursion: Typically more concise code | Iteration: Can be more efficient in terms of memory and speed. Recursion: Uses the call stack | Iteration: Does not use the call stack.
What is the definition of Recursion?
A way to simplify problems by having a subproblem that calls itself repeatedly.
What is the definition of a Recursive Method?
A method that has two parts: a base case and the recursive call.
What is the definition of a Base Case?
The last recursive call. When the base case is reached, the recursion is stopped and a value is returned.
What is the definition of Recursive Call?
A call to the recursive method itself, telling it to start over, either with the same or different parameters.
What is the definition of a Call Stack?
A stack that keeps track of all the times that the recursive function is called, as well as their individual parameters.
What does the following code output?
java
public static int multiply(int a, int b) {
if (b == 0) {
return 0;
} else {
return multiply(a, b - 1) + a;
}
}
System.out.println(multiply(5, 3));
15
Identify the error in the following code:
java
public static void recursiveMethod() {
do something
recursiveMethod(); // recursive call
}
Missing base case, which will cause infinite recursion and a stack overflow error.
What does the following code output?
java
public static void traverseArray(ArrayList<Integer> array, int startIndex) {
if (startIndex == array.size() - 1) { // base case
System.out.println(array.get(startIndex));
} else { // recursive case
System.out.println(array.subList(startIndex, array.size()).get(0));
traverseArray(array, startIndex + 1);
}
}
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 3));
traverseArray(arr, 0);
1 2 3