Successive subtraction, what am I missing?

The place for codemasters or beginners to talk about programming any language for the Spectrum.
Post Reply
KayBee
Drutt
Posts: 17
Joined: Thu May 31, 2018 3:14 pm

Successive subtraction, what am I missing?

Post 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
User avatar
1024MAK
Bugaboo
Posts: 3104
Joined: Wed Nov 15, 2017 2:52 pm
Location: Sunny Somerset in the U.K. in Europe

Re: Successive subtraction, what am I missing?

Post 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
:!: Standby alert :!:
“There are four lights!”
Step up to red alert. Sir, are you absolutely sure? It does mean changing the bulb :dance
Looking forward to summer later in the year.
KayBee
Drutt
Posts: 17
Joined: Thu May 31, 2018 3:14 pm

Re: Successive subtraction, what am I missing?

Post by KayBee »

Man, now that you say that it is so obvious...got it. Thank you 1024MAK.

KB
Post Reply