Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
This pseudocode works on a whole number that is input.
DECLARE Number : INTEGER
DECLARE Sum : INTEGER
Sum ← 0
INPUT Number
WHILE Number > 0 DO
Sum ← Sum + MOD(Number, 10)
Number ← DIV(Number, 10)
ENDWHILE
OUTPUT SumComplete a trace table for the input 4083, with the columns Number and Sum. How many times does the loop run, and what is output? What does the program do, in one sentence?
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.
The trace table. The first row is the input, then one row for each pass.
Number 4083, Sum 0Number 408, Sum 3Number 40, Sum 11Number 4, Sum 11Number 0, Sum 15Count. The loop ran 4 times, once for each digit. The output is 15.
What it does. It adds up the digits of the number: .
Check. The digit 0 adds nothing, so Sum stays 11 in the third pass. That is a good place to check your own table.
Watch out. A WHILE loop tests first. For the input 0 it runs no times and outputs 0, which is the right digit sum.
Log in to join the discussion.
Loading…