Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A program tries to move everyone in a queue back one place, to make room at the front.
DECLARE Queue : ARRAY[1:5] OF STRING
DECLARE n : INTEGER
Queue[1] ← "Ali"
Queue[2] ← "Bo"
Queue[3] ← "Cy"
Queue[4] ← "Di"
Queue[5] ← "Ed"
FOR n ← 1 TO 4
Queue[n + 1] ← Queue[n]
NEXT nAfter the loop, how many elements hold "Ali"? Correct the loop so that the queue moves back properly, and put "Zoe" at the front.
DECLARE Name : ARRAY[Lower:Upper] OF TYPE makes a fixed-length array of one data type. An element is Name[Index], and the index may be a variable or an expression. A FOR loop from the lower bound to the upper bound visits every element. Pseudocode arrays usually start at 1; Python lists at 0.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. The trace. When n is 1, Queue[2] becomes "Ali". When n is 2, Queue[3] takes Queue[2], which is now "Ali". The same happens for n = 3 and n = 4. All 5 elements hold "Ali", and the other names are lost.
Step 2. The correction. Copy from the back first, so each name moves before it is overwritten. "Ed" falls off the end, as the array has only 5 places.
FOR n ← 4 TO 1 STEP -1
Queue[n + 1] ← Queue[n]
NEXT n
Queue[1] ← "Zoe"Check. The queue is now Zoe, Ali, Bo, Cy and Di.
Answer: 5 elements hold "Ali". The loop must run from 4 down to 1.
Log in to join the discussion.
Loading…