Hi again ...
Okay, no problem... let's start off with the first question...
here we see the loop setup to run in reverse. So let break it down... ( you all ready know the for loop syntax, so I explain the code within...
we initilize int i to be bits.length which using a 4 element array as an example would return a length of 4, but arrays are 0 indexed, so the last element in that array would be 3, so we subtract 1 to correct it.
basically, once we reach 0, end the loop
each iteration decrements i by 1... a count down until it reaches 0 which ends the loop...
then we setup the loop so that is start with the right most element.
here i called "i" index for clarity...
next we check if the element is 1, if so then we add it binary value to our answer variable
so now we are almost at the end of the loop, before we go to the next element to the left, we need to increase our exponent value by 1
and the loop will count down until 0 is reached...
So using the example again using a 4 element array...
1-0-1-0 <- our char array representing a binary number 1010
0-1-2-3 <- our char array index values for each element in the char array
3-2-1-0 <- the exponent that we raise 2 by ( Math.pow(2.0,powers))
let step through it...
on the loops first run our index (index)starts at 3 (index = bits.length-1)
and our exponent (powers) is 0
at index 3, our binary number (bits[index]) is '0' so no math is done
answer current is 0
now that the check is done we increment our exponent (powers) by one (powers++)
on then second run of our loop, our index (index) is now 2 (index--)
and our exponent (powers) is now 1
at index 2, our binary number (bits[index]) is now '1' so we do the math (answer += Math.pow(2.0,powers)
answer is now 2
and all that done we increment our exponent (powers) by one again (powers++)
on the third run of out loop, you guessed it... index (index) is now 1 (index--)
our exponent (powers) is now 2
and at index 1, our binary number (bits[index]) is again '0' so no math
answer is still 2
and again we increment our exponent (powers) by one (powers++)
on the four and final run of our loop, index (index) is now 0 (index--)
our exponent (powers) has now reached 3
at index 0, our binary number (bits[index]) in '1' so we do the math (Math.pow(2.0,powers)
and answer is now 10 ( 2 + 8 )
although we still increment our exponent (powers) we no longer need it since our loop has ended...
Hopefully this helps...
[ February 09, 2005: Message edited by: Liam Tiarnach ]