One of the most important tasks that you will need to be able to do with arrays is to search them for specific values. Small Basic gives an easy way to find out if a value is in an array but it doesn’t tell us where it is. Small Basic really needs a function ‘Array.GetIndexOf()’ but it doesn’t have one so we need to be able to program it ourselves. It will be useful whenever we work with arrays and/or files.
To do it we need to analyse how we, as humans (assuming you are), search through a list and decide if we have found an entry (or not). We are going to assume that the list is not in any particular order as this does affect how we work.
With an un-ordered list, we have to start at the beginning (or end) of the list and work through each entry until we either find the required element or we get to the other end of the list.
In an unordered list there will only be these two outcomes, We either find the element we are looking for or we arrive at the end of the list.
This implies that for our program, we need to continually check for these two outcomes. Below I have set this out in pseudo code and as a flow chart.
Notice that the While… …EndWhile loop checks to see if the entry was found AND if we are NOT at the end of the list. Inside this loop a simple If… …Then… …Else decision just checks to see if the entry has been found.
When the code finishes, all we need to do is check to see if the variable ‘Found’ is True. If it is then the data was found and the value held in ‘Index’ is the index to the required data in the array. We can then do whatever we need with the Array[ Index ] data. Of course this algorithm has assumed that the array uses numeric indexes but it can be modified to work with word indexes if required.