4 ms·
There are other interesting reasons why it is better to use zero-based indexing. In some algorithms you need to access n-th element modulo something. For exampl
by ingenter 13y ago
There are other interesting reasons why it is better to use zero-based indexing.
In some algorithms you need to access n-th element modulo something.
For example, to fill an array of arrays, in zero-based array
for (i = 0; i < width*height; i++) {
arr2d[i / width][i % width] = array[i];
}
If you use one-based arrays, you have to write
for (i = 1; i <= width*height; i++) {
arr2d[(i-1) / width + 1][(i - 1) % width + 1] = array[i];
}
Yes, you can write two loops, but this example shows how mapping one array onto another is easier if you use zero-based array.
- cousin_it 13y agoGood point. You could also say that simulating two-dimensional arrays with one-dimensional arrays is easier with zero-based indexing: a[x + y * w] rather than a[x + (y - 1) * w]. Are there similar use cases that look more natural with one-based indexing?
- htns 13y agoThis becomes just as simple in one-based indexing if you take the negative view and have division round up and modulo run from (-n + 1) to 0 instead of 0..(n - 1). So you get "arr2d[i / width + 1][i % width] = array[i]" if your language does the logical thing with non-positive indexes. Using modular arithmetic to argue for zero-based indexing is close to circular reasoning.
- userbinator 13y agoI can remember that out of all the code I've written, I've very rarely needed a +1/-1 except as part of accessing a next/previous element, so at least from this data point, zero-based indexing makes the code simpler and easier to understand. That second example of yours I had to spend a lot more time reading (and mentally doing increments/decrements) to figure out. I'm almost willing to bet there would be more off-by-one errors if one-based somehow became the norm.