Recursion

AP Computer Science A· difficulty 5/5

public static int f(int n) {
    if (n <= 1) return 1;
    return f(n - 1) + f(n - 2) + 1;
}
System.out.println(f(4));

What is printed?

  • A

    7

  • B

    5

  • C

    9

    check_circle
  • D

    11

Explanation

f(0)=1,f(1)=1,f(2)=1+1+1=3,f(3)=3+1+1=5,f(4)=5+3+1=9.

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

Related questions