AP Computer Science A : Programming Constructs

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

varsity tutors app store varsity tutors android store

Example Questions

Example Question #71 : Program Implementation

The Fibonacci sequence is a classic example of: _________

Choose the best answer.

Possible Answers:

None of the above

Iteration

Selection

Recursion

Correct answer:

Recursion

Explanation:

The Fibonacci sequence is known as a recurrence relation in mathematical terms. In programming, we represent recurrence relations using recursive methods or simply recursion. The Fibonacci sequence is a great example of recursion. 

Example Question #221 : Computer Science

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:

12

3

8

5

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