Successive subtraction, what am I missing?

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

Successive subtraction, what am I missing?

Post by KayBee » Fri Jan 11, 2019 2:49 pm

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
0 x

User avatar
1024MAK
Manic Miner
Posts: 532
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 » Fri Jan 11, 2019 3:10 pm

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
0 x

KayBee
Berk
Posts: 17
Joined: Thu May 31, 2018 2:14 pm

Re: Successive subtraction, what am I missing?

Post by KayBee » Sun Jan 13, 2019 4:07 pm

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

KB
0 x

Post Reply