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()
- Atop = 2, st = {5, 3, 0, 0, 0}
- Btop = 2, st = {5, 3, 7, 0, 0}
- 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.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions