SOLVED EXERCISES

PAGE 1 / 4

The while Statement
REQUIREMENT
A natural number
n is read. Print the number obtained by reversing the positions of its digits.
Example. If we read
n=248, we print
842.
SOLUTION
Consider two numbers: the second number is obtained from the first by adding a digit at the end (
456 and
4563). We have the relationship:
4563 = 456 * 10 + 3
Obviously, the relationship holds true for any two natural numbers that satisfy the above condition. It's clear that the reversed number will start with the last digit of the number read. Let's assume we read
248. We'll build the reversed number like this:
8=0*10+8
(8 is the last digit of the read number and the remaining number is 24)
84=8*10+4
(4 is the last digit of the remaining number and the remaining number is 2)
842=84*10+2
(2 is the last digit of the number 2 and the remaining number is 0)
Review the resulting program:
Review the solved problem,
then proceed to the next page.