Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Dry-run this algorithm with the input , and then state its purpose.
INPUT Number
Result ← 0
WHILE Number > 0 DO
Result ← Result * 10 + MOD(Number, 10)
Number ← DIV(Number, 10)
ENDWHILE
OUTPUT ResultA 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. Pass 1. Result ← 0 * 10 + 6 = 6. Number ← 58.
Step 2. Pass 2. Result ← 6 * 10 + 8 = 68. Number ← 5.
Step 3. Pass 3. Result ← 68 * 10 + 5 = 685. Number ← 0.
Step 4. 0 > 0 is false, so the loop ends and is output.
Answer: the output is . The purpose: it inputs a positive whole number and outputs the number with its digits in reverse order.
What if? For the input the output is : the leading zero of 021 disappears, because Result is a number, not text.
Log in to join the discussion.
Loading…