AP Computer Science A : Recursion

Study concepts, example questions & explanations for AP Computer Science A

varsity tutors app store varsity tutors android store

Example Questions

Example Question #71 : Programming Constructs

public int foo(int n)

{

    if (n < 0)

        return 1;

    else

        return foo(n-2) + foo(n-1)

}

What is the value returned by foo(3)?

Possible Answers:

8

3

5

12

6

Correct answer:

8

Explanation:

The answer is 8.

This question tests knowledge of recursion. The correct strategy is to build a tree of function calls. Since the base case of foo returns 1, we can just add up all the function calls that return the base case. In the tree below, the green functions represent the base cases, with an argument less than 0. 

Foo

Learning Tools by Varsity Tutors