Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A box office sells from 1 to 6 tickets to one person. This pseudocode asks again until the number is in range, and counts the tries.
DECLARE Tickets : INTEGER
DECLARE Tries : INTEGER
Tries ← 0
REPEAT
OUTPUT "How many tickets? (1 to 6)"
INPUT Tickets
Tries ← Tries + 1
UNTIL Tickets >= 1 AND Tickets <= 6
OUTPUT "Tries: ", TriesA customer types 0, then 9, then 4. How many times is the prompt output, and what is the last line of output? Explain why a REPEAT loop is the right choice here.
FOR Count ← A TO B STEP S ... NEXT Count runs a known number of times. WHILE <condition> DO ... ENDWHILE tests first and may run no times. REPEAT ... UNTIL <condition> tests last and runs at least once. A total adds each value; a count adds 1. A trace table records every variable and output at each step.
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. First pass. The prompt is output and Tickets is 0. Tries is 1. 0 >= 1 is FALSE, so the condition is FALSE and the loop runs again.
Step 2. Second pass. The prompt again, Tickets is 9, Tries is 2. 9 <= 6 is FALSE, so the loop runs again.
Step 3. Third pass. The prompt a third time, Tickets is 4, Tries is 3. Both parts are TRUE, so the loop stops. The last line is Tries: 3.
Why REPEAT. The customer must be asked at least once, and the test can only be made after the input. A REPEAT loop tests at the end, so it fits. A WHILE loop would need an extra INPUT before the loop.
Answer: the prompt appears 3 times, and the last line is Tries: 3.
Log in to join the discussion.
Loading…