# help with a Loop(arithmetic)

Printable View

• 01-25-2012, 11:01 PM
derb2k2
help with a Loop(arithmetic)
premise of this is to reverse any number(<10 digits) entered by user and print it.

int number, lastDigit, reverse = 0;

number = scan.nextInt();

do
{
lastDigit = number % 10;
reverse = (reverse * 10) + lastDigit;
number = number / 10;
}
while (number > 0);

print reverse...

What i'm having trouble with is the logic of the arithmetic. e.g. "number" entered is 678, then lastDigit = 8. Considering the reverse equation, then what does "reverse" equal to and how is it able to reverse the number entered?
• 01-26-2012, 12:47 AM
eRaaaa
Re: help with a Loop(arithmetic)
1.loop:
-----
lastDigit = 678%10 = 8
reverse = 0*10 + 8 = 8
number = 678/10 = 67

2.loop
-----
lastDigit = 67%10 = 7
reverse = 8*10 + 7 = 87
number = 67/10 = 6

3.loop
-----
lastDigit = .....
......
.....
was that your question? sorry if not :-)
• 01-26-2012, 02:50 AM
joshdgreen
Re: help with a Loop(arithmetic)
I have another question for you, did you write the arithmetic yourself or was this a code given to you to play around with to make it work? I keep running through the arithmetic in my head and it doesn't seem like it would work to me, so I just wanted to make sure before I say anything else.
• 01-26-2012, 01:41 PM
derb2k2
Re: help with a Loop(arithmetic)
this is from a Java book. Java software solutions by Lewis and Loftus. The figures are the same as in the book. The program returns and answer of 876

Eraa I'm looking into your reply now. Thank you.
• 01-26-2012, 01:58 PM
derb2k2
Re: help with a Loop(arithmetic)
Quote:

Originally Posted by eRaaaa
1.loop:
-----
lastDigit = 678%10 = 8
reverse = 0*10 + 8 = 8
number = 678/10 = 67

2.loop
-----
lastDigit = 67%10 = 7
reverse = 8*10 + 7 = 87
number = 67/10 = 6

3.loop
-----
lastDigit = .....
......
.....
was that your question? sorry if not :-)

Ah so the second loop takes number from the first loop, and then implements that and so on? I see the logic of it now. But
doesn't the bold equation( 678/10 ) equal 67 remainder 8? What do you do with the 8 when using 67 in the second loop?

okay so "number" is an int? is that why number = 678/10 = 67 ends up 67? forgive my noobishness lol
• 01-26-2012, 02:09 PM
eRaaaa
Re: help with a Loop(arithmetic)
number is an integer, so there is no remainder! 678/10 -> number = 67
System.out.print(678/10) - the remainder (the eight) is saved in lastDigit with the help of the modulo operator!
• 01-26-2012, 02:15 PM
derb2k2
Re: help with a Loop(arithmetic)
tytytyt I will run through this once again after I get some food in me xD