Search

mercredi 8 février 2017

Null values in arrays

Context

As mentioned in this previous post, array implementation induces a limitation: elements cannot be null. Let's now see how to deal with zeros.
To access an element in an array, we need to go through all elements, so use a loop. And loops stop when value reached is null. Therefore, our current array structure doesn't fit.

However, it's still possible to have arrays with 2 memory cells per element: first that contains a non-zero value (any value, but let's say 1), and second that contains the actual element value.
Then, to access elements in the array, we need to iterate on blocks of 2 cells.

Code sample

>>+ first separator
>>, read char
[
  >++++[-<----------->]+< comma check
  [---- convert to digit value
    >++++++++[-<<[->+>>+<<<]>>>[-<<<+>>>]<]<[-<+>] multiply current by ten and add new digit
  ]>[ comma case
    <+>->> add cell with 1 and start next number
  ]<,]
<<[<<]>> go back to array last element (first cell) then back to the array beginning
This block of code read comma-separated decimal numbers, including 0, and store them in memory cells separated by cells containing 1.


The last line shows how to move back to the array first element.

Aucun commentaire:

Enregistrer un commentaire