I was trying to make my own version of minesweeper for TI 84 Plus CE, and I was working on the mine randomization loop, but for some reason, it was exiting the loop before the For( loop had reached its end value.
The code looked a little like this

Code:


For(A,1,M)
Lbl 1
"M is mine count"
randInt(1,S*T)→B
"S and T are the  board dimensions"

If ʟMINE(B)=9
Then
"ʟMINE is the list where the state of the board is stored, and 9 signifies a mine"
Goto 1
Else
9→ʟMINE(B)
End

End



Now, let's say I wanted 50 mines, I would test it out, and the loop would exit before A even reaches 10. I want to know why this might be as I'm very confused as to why this would happen.

PS, I know that the way I wrote things isn't ideal in the slightest, I have moved on to a different method that's far better, but I still want to know why this didn't work.
Generally, Goto within a loop is a recipe for disaster thanks to how the calculator tracks End statements.

Every time the interpreter enters a construct which requires an End, it pushes some data to a stack, only popping that entry once it hits an End. Since you Goto out of an If:Then, its End is never reached, so that If:Then is still "open". Returning to the top of the loop, that If:Then will then be pushed to the stack a second time.

So now we have three things on the stack, the For( and two If:Then's, but only two End's to close them. Thus, the For( is left open at the final line of the program, so it does not loop, and all execution terminates.

This behavior can be used to your advantage to implement "subroutines" (keyword for searching is "gosub"), but barring this use case is to be avoided. Even if your loop proceeded correctly, repeatedly pushing to the stack without popping will eventually overflow its memory, crashing the program; these are called "memory leaks". If you want to conditionally Goto, use a single-line If, as it has no End to track.
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement