AP Computer Science A · Topic 10.1
Recursion Practice
Part of Recursion.
Practice questions
96
Sample questions
5 of 96 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
public static int sumRec(int n) { if (n == 0) return 0; return n + sumRec(n - 1); } public static int sumIter(int n) { int s = 0; for (int i = 1; i <= n; i++) s += i; return s; }Which is true?
- A
Iteration cannot solve this
- B
They produce different sums
- C
Recursive version uses less memory
- Dcheck_circle
Both compute the same result; iteration uses less stack
Why
Both sum 1..n. Recursion creates O(n) stack frames; iteration uses O(1) stack.
- A
Sample 2difficulty 2/5
public static int sum(int[] a, int i) { if (i >= a.length) return 0; return a[i] + sum(a, i + 1); } // call: sum({1,2,3,4}, 0)What does the call return?
- A
6
- B
0
- C
4
- Dcheck_circle
10
Why
1+2+3+4 = 10.
- A
Sample 3difficulty 2/5
public static int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } // call: fact(5)What does fact(5) return?
- A
60
- B
24
- C
5
- Dcheck_circle
120
Why
5! = 5<em>4</em>3<em>2</em>1 = 120.
- A
Sample 4difficulty 2/5
A recursive method
- A
Uses static fields
- B
Loops forever
- C
Cannot return values
- Dcheck_circle
Calls itself (directly or indirectly)
Why
Recursion: method invokes itself with smaller subproblem.
- A
Sample 5difficulty 2/5
public static int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } System.out.println(fact(4));What is printed?
- A
6
- Bcheck_circle
24
- C
12
- D
10
Why
fact(4) = 4<em>3</em>2*1 = 24. The base case returns 1 when n <= 1.
- A