Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Dry-run this algorithm and complete a trace table with the columns A, B and OUTPUT.
A ← 7
B ← 3
REPEAT
A ← A - B
B ← B + 1
UNTIL A < B
OUTPUT A, " ", BWhat are the final values of A and B, and how many times does the loop body run?
A dry run follows an algorithm by hand. A trace table has a column for each variable and for the output, which includes the user prompts. Write a value only when it changes, and start a new row for each pass of a loop.
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. Start. A is and B is .
Step 2. Pass 1. A ← 7 - 3 = 4, then B ← 4. Test 4 < 4: false, so repeat.
Step 3. Pass 2. A ← 4 - 4 = 0, then B ← 5. Test 0 < 5: true, so stop.
Step 4. Output. 0 5.
The trace table, one row per value of A:
A , B ;A , B ;A , B , output 0 5.Answer: A is , B is , and the loop body runs times.
Watch out. In pass 1 the test uses the new B, which is , not the old . With the old value the loop would stop one pass early.
Log in to join the discussion.
Loading…