Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A sports watch records the length of a run in minutes. This algorithm turns the minutes into hours and minutes.
INPUT Minutes
Hours ← DIV(Minutes, 60)
Left ← MOD(Minutes, 60)
OUTPUT Hours, " hours ", Left, " minutes"DIV and MOD do in this algorithm.Cambridge pseudocode: keywords in capitals, names in mixed case, ← for assignment, INPUT and OUTPUT, IF ... THEN ... ELSE ... ENDIF, CASE OF ... OTHERWISE ... ENDCASE, FOR ... TO ... STEP ... NEXT, WHILE ... DO ... ENDWHILE, REPEAT ... UNTIL. DIV(a, b) is the whole-number quotient and MOD(a, b) the remainder.
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. DIV. DIV(135, 60) is the whole number of times goes into . , and is too big. So Hours is .
Step 2. MOD. MOD(135, 60) is the remainder: . So Left is .
Answer: (a) the output is 2 hours 15 minutes. (b) DIV gives the number of whole hours, and MOD gives the minutes left over.
What if? For an input of the output is 0 hours 59 minutes. For it is 1 hours 0 minutes. A careful programmer might amend the message for one hour.
Log in to join the discussion.
Loading…