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?

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 :-)

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.

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.

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

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!

Re: help with a Loop(arithmetic)

tytytyt I will run through this once again after I get some food in me xD