Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A number has three digits, for example 472. Write a program that shows its hundreds digit, tens digit and ones digit, using only // and %. Test it with 472, 905 and 100.
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.
Plan. The ones digit is the remainder after dividing by 10. To get the tens digit, first remove the ones digit with // 10, and then take the remainder again. The hundreds digit is what is left after removing two digits.
472 % 10 is 2, the ones digit.472 // 10 is 47, and 47 % 10 is 7, the tens digit. The line number // 10 % 10 does both in order, left to right.472 // 100 is 4, the hundreds digit.Test. For 905: 5, 0 and 9. For 100: 0, 0 and 1. Both work.
Check. Put the digits back together: 4 * 100 + 7 * 10 + 2 = 472.
Answer: The program above shows 4 7 2.
Log in to join the discussion.
Loading…