Programming Basics (Pseudocode Tracing)

A stack is represented by the 5-element integer array st and the integer variable top. All elements of st start at 0 and top starts at 0. push(v) adds 1 to top and then does st[top] ← v; pop() returns the value of st[top] and then subtracts 1 from top (the elements of st are not changed). What are top and st after the following program runs?

push(5)
push(8)
pop()
push(3)
push(9)
pop()
push(7)
pop()
  1. Atop = 2, st = {5, 3, 0, 0, 0}
  2. Btop = 2, st = {5, 3, 7, 0, 0}
  3. Ctop = 5, st = {5, 8, 3, 9, 7}
Show answer and explanation

Answer: B. top = 2, st = {5, 3, 7, 0, 0}

push(5) and push(8) give st[1] = 5, st[2] = 8 and top = 2, and pop() returns 8, leaving top = 1. push(3) overwrites st[2] with 3, push(9) sets st[3] = 9, and pop() brings top back to 2. push(7) overwrites st[3] with 7, and the last pop() makes top = 2. pop() only decreases top, so the popped 7 remains in st[3]: st = {5, 3, 7, 0, 0}. The valid stack contents are st[1] to st[top], that is, 5 and 3.

  • A. This assumes pop() clears the element to 0. pop() only decreases top.
  • B. Correct. top = 2, and the popped 7 remains in st[3].
  • C. This assumes pop() does not decrease top and every push appends at the end.
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. A queue uses the 4-element string array q as a ring. head and tail start at 1. enq(v) does q[tail] ← v and then tail ← tail mod 4 + 1; deq() returns the value of q[head] and then does head ← head mod 4 + 1. When the following program runs, in which element of q is "E" stored?
  2. The following program outputs a linked list, whose elements are linked by the array next, by following it from the element at index 1. Array indices start at 1. A next value of 0 marks the end of the list. What sequence of values is output?
  3. The following program inserts "F", in val[6], right after "C" (index 3) in the linked list A → C → E → D → B, linked by the array next, and then outputs the list from the element at index 1. Array indices start at 1. A next value of 0 marks the end of the list. What should replace 【a】 so that the output is A, C, F, E, D, B?
  4. The following for loop increases its control variable by 5. What is the value of c after it runs?
  5. In the following program, and does not evaluate its right side when the left side is false (short-circuit evaluation). cnt is a global variable. What is the value of cnt after the program runs?