Computer Science : Programming Constructs

Study concepts, example questions & explanations for Computer Science

varsity tutors app store varsity tutors android store

Example Questions

1 2 3 4 5 6 8 Next →

Example Question #11 : Recursion

The Fibonacci sequence is a classic example of: _________

Choose the best answer.

Possible Answers:

Selection

None of the above

Recursion

Iteration

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 #11 : Recursion

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

5

6

8

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

1 2 3 4 5 6 8 Next →
Learning Tools by Varsity Tutors