Recursion

AP Computer Science A· difficulty 4/5

public static int f(int n) {
    if (n <= 1) return 1;
    return f(n-1) + 2 * f(n-2);
}
// Call: System.out.println(f(5));

What is printed?

  • A

    21

    check_circle
  • B

    31

  • C

    11

  • D

    32

Explanation

f(0)=1, f(1)=1. f(2)=f(1)+2<em>f(0)=1+2=3. f(3)=f(2)+2</em>f(1)=3+2=5. f(4)=f(3)+2<em>f(2)=5+6=11. f(5)=f(4)+2</em>f(3)=11+10=21.

Want 10 more like this — adaptive to your weak spots?

Related questions