[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: coding question



PureBytes Links

Trading Reference Links

> everytime the loop or the if...then statement populate myarray I
> use counter = counter + 1 to prepare it for the next value. 
> 
> can some one tell me what's wrong with this code?

That's a little hard because you didn't say what happens.  But I 
would guess you keep incrementing counter = counter + 1 -- even when 
you've already put 10 values in the array.  (Or 11, if you prefer, 
since myarray[10] goes from element 0 to 10.  But I'll assume you're 
only using positions 0 through 9.)

If you keep incrementing counter, then the line that copies the last 
two values to positions 0 and 1 will try to access past the end of 
the array.

You will have to detect if counter is already 10 before you try to 
increment it and, if so, shift all the values by one to make room.  
I.e. put 1 into 0, 2 into 1, ... 10 into 9, and then insert your new 
value into position 9.  And don't let the counter get greater than 10.

You could also use what's called a "circular array," where instead of 
shifting values when the array is full, you wrap around to the 
beginning.  I.e. fill element 0, 1, 2, .... 8, 9, then 0, 1, 2, ...  
When you wrap around and insert a new value in 0, then your new 10-
long array starts in element 1.  When you insert another value in 
position 1, the array starts at position 2.  Use a "modulo" function 
to wrap your index into the array:  

  myarray[mod(counter, 10)] = NewValue;
  counter = counter + 1;

Then you just have to make sure your "virtual array" starts in the 
right place.  You have inserted "counter" values in it, but there are 
no more than 10 values in it now.  The starting point of the array is 
at myarray[mod(counter+9, 10)].  (That assumes counter is 0 before 
you insert any values, then you insert them as shown above.  The 
first value is in position 0.)

Usually the circular array is used when you have a much longer array, 
and shifting it is too expensive.  With a short array like yours, 
it's probably a lot simpler to just shift it.

Gary