Programming Basics (Pseudocode Tracing)

What does the following function s return when called as s(7)?

○integer: s(integer: n)
  if (n ≦ 0)
    return 0
  endif
  return n + s(n − 2)
  1. A15
  2. B16
  3. C28
Show answer and explanation

Answer: B. 16

s(7) calls s(5) to compute 7 + s(5), s(5) calls s(3) for 5 + s(3), s(3) calls s(1) for 3 + s(1), and s(1) calls s(−1) for 1 + s(−1); s(−1) returns 0 because n ≦ 0. The values are added as the calls return, giving s(7) = 7 + 5 + 3 + 1 + 0 = 16. This is the sum of the positive odd numbers up to 7.

  • A. This assumes 0 is returned for n ≦ 1, giving 7 + 5 + 3. In fact s(1) returns 1 + s(−1) = 1.
  • B. Correct. 7 + 5 + 3 + 1 = 16.
  • C. This assumes s(n − 1) is called, giving 7 + 6 + … + 1.
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 procedure p is called as p(3), what sequence of values is output?
  2. What does the following function fib return when called as fib(10)?
  3. When the following function c is called as c(4, 2), how many times is c called, including the first call?
  4. ⊕ is bitwise exclusive OR. What are the values of x and y 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. What is the value of y after the following program runs?