Computer Science : Programming Constructs

Study concepts, example questions & explanations for Computer Science

varsity tutors app store varsity tutors android store

Example Questions

Example Question #1 : Recursion

The Fibonacci sequence is a classic example of: _________

Choose the best answer.

Possible Answers:

None of the above

Selection

Iteration

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 #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