Programming Basics (Pseudocode Tracing)

What does the following function fib return when called as fib(10)?

○integer: fib(integer: n)
  integer: a ← 0, b ← 1, t
  for (i from 1 to n step 1)
    t ← a + b
    a ← b
    b ← t
  endfor
  return a
  1. A34
  2. B55
  3. C89
Show answer and explanation

Answer: B. 55

Each pass advances (a, b) by one pair of adjacent Fibonacci numbers: (0, 1) → (1, 1) → (1, 2) → (2, 3) → (3, 5) → (5, 8) → (8, 13) → (13, 21) → (21, 34) → (34, 55) → (55, 89). After 10 passes the function returns a = 55. After the i-th pass, a is the i-th Fibonacci number. A naive recursive version computes the same values many times, but this one needs only n passes.

  • A. This is the value with one pass fewer (final value n − 1).
  • B. Correct. a = 55 after 10 passes.
  • C. This is the value of b, the 11th Fibonacci number.
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. When the following function c is called as c(4, 2), how many times is c called, including the first call?
  2. ⊕ is bitwise exclusive OR. What are the values of x and y after the following program runs?
  3. x and y are 8-bit unsigned integers. << and >> are logical shifts: vacated bits are filled with 0, and bits shifted out of the 8 bits are discarded. ∨ is bitwise OR. What is the value of y after the following program runs?
  4. ∧ is bitwise AND. What is the value of c after the following program runs?
  5. x and y are 8-bit unsigned integers. << and >> are logical shifts: vacated bits are filled with 0, and bits shifted out of the 8 bits are discarded. ∨ is bitwise OR. With x = 75, what is the value of y after the following assignment?