zuai-logo
zuai-logo
  1. AP Computer Science A
FlashcardFlashcard
Study GuideStudy GuideQuestion BankQuestion BankGlossaryGlossary

What is the purpose of the base case in recursion?

To stop the recursion and return a value, preventing an infinite loop.

Flip to see [answer/question]
Flip to see [answer/question]
Revise later
SpaceTo flip
If confident

All Flashcards

What is the purpose of the base case in recursion?

To stop the recursion and return a value, preventing an infinite loop.

What is the role of the call stack in recursion?

To keep track of all the recursive calls and their parameters, allowing the program to return values correctly.

What is the trade-off between recursion and iteration?

Recursion is often simpler to read but can be slower and use more memory due to the call stack.

How can recursion simplify problem-solving?

By breaking down a large problem into smaller, self-similar subproblems that can be solved repeatedly.

What are the two main parts of a recursive method?

The base case and the recursive call.

What is the relationship between recursion and iteration?

All recursive code can be written iteratively using loops.

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

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.