WRITE A PROGRAM USNG WHILE LOOP TO REVERSE THE DIGITS OF THE NUMBER.
Hint : use the modulus operator to extract the last digit and the integer division by 10 to get the n-1 digit number from the n digit number.
NO IS - 12345
ANS IS 54321
Answers
Answer:
Using Python:
starting_number = 12345
number = starting_number
ending_number = 0
while (number > 0):
remainder = number % 10
ending_number = (ending_number * 10) + remainder
number = number // 10
print(f"Starting number: {starting_number}")
print(f"Ending number: {ending_number}")
print("Starting number: " + starting_number)
print("Ending number: " + ending_number)
Explanation:
You didn't specify what language you were using, so I'll be using Python. We'll have a look at this a line at a time. You can have a look at the image attached to see how the numbers change
First we need to set up our variables.
starting_number will be the number printed at the end.
> starting_number = 12345
number will be used in our while loop.
> number = starting_number
ending_number will be our final answer.
> ending_number = 0
Now we initialize our while loop
While the given number variable is more than 0. (don't forget: number = starting_number)
> while (number > 0):
Using the modulus operator, you can get the number at the end of your starting_number variable.
> remainder = number % 10
Multiply your ending number by ten and add the remainder variable above.
> ending_number = (ending_number * 10) + remainder
Finally, divide your number variable by ten to do your next number
> number = number // 10
Printing
Once our while loop is complete, when number <= 0, we can finally print our answer.
> print(f"Starting number: {starting_number}")
> print(f"Ending number: {ending_number}")