Page 1 of 1

Successive subtraction, what am I missing?

Posted: Fri Jan 11, 2019 2:49 pm
by KayBee
Hi Again BASIC people,

I am missing something here, but I cannot put my finger on it. I have an array of random numbers, and want to subtract each value from the one preceding it:

205 DIM x(5)
210 FOR a=5 TO 2 STEP -1
215 LET x(a)=INT (RND*10)+1
250 PRINT "x(a)=";x(a);" x(a-
1)=";x(a-1)
305 PRINT "x(a)-x(a-1)=";x(a)-x
(a-1)
325 NEXT a
330 PRINT

But the subscript subtraction is not working. What am I missing?

Cheers, and thank you folks.

KB

Image

Re: Successive subtraction, what am I missing?

Posted: Fri Jan 11, 2019 3:10 pm
by 1024MAK
Because you are only filling the array up with one value per loop, but are asking in the PRINT statement for a value that has not yet been stored, hence BASIC is returning the default value of zero. A numeric array is set up with all array elements having the value zero when the DIM statements is processed.

So for the first run through the loop, a value is stored at x(5).
Then lines 250 and 305 both ask for a value of x(5-1), which is x(4). X(4) contains 0 (zero) as your program has not yet stored a number there. So BASIC returns the default value of 0 (zero).

This continues at each pass of the loop, with lines 250 and 305 each time asking for a value that has not yet been stored...

Mark

Re: Successive subtraction, what am I missing?

Posted: Sun Jan 13, 2019 4:07 pm
by KayBee
Man, now that you say that it is so obvious...got it. Thank you 1024MAK.

KB