ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (number of ways to climb n stairs, taking 1 or 2 steps at a time)?

What will be the output of the following pseudocode (number of ways to climb n stairs, taking 1 or 2 steps at a time)?
Function climb(Integer n)
    if (n <= 2)
        return n
    end if
    Integer a = 1, b = 2
    for (each i from 3 to n)
        Integer temp = a + b
        a = b
        b = temp
    end for
    return b
End Function

Print climb(5), climb(8)
  1. A. 8 34
  2. B. 5 13
  3. C. 8 21
  4. D. 13 34

Correct answer: A. 8 34

This is the Fibonacci-like staircase recurrence: climb(5)=8 and climb(8)=34, matching the Fibonacci sequence shifted by one position.

More Pseudocode and Code Tracing questions

Exams that ask this topic