In today’s article, I want to discuss a dualism present in programming languages.
What it could be?
I think in some matter we can notice this fact in very different aspects related to the programming languages. But, today I want to discuss how different programming languages process array indexes.
So there are programming languages with 0-based and 1-based indexes for arrays. The programming languages with 0-based indexes apply zero-based numbering approach when the initial element of a sequence is assigned the index 0.
The programming languages with 1-based indexes are based on the one-based numbering approach when the initial element of a sequence is assigned index 1.
A first group includes programming languages so-called general-purpose programming languages. There are some of them in the table below:
Array Index Type | Programming Language |
---|---|
0-based | C |
0-based | C++ |
0-based |
C# |
0-based |
Java |
0-based | Python |
0-based | JavaScript |
0-based | PHP |
0-based | Ruby |
At the same time, programming languages with 1-based indexes have mostly mathematical nature and used for mathematical and scientific calculations. Some of the examples right below in the table:
Array Index Type | Programming Language |
---|---|
1-based | Fortran |
1-based | MATLAB |
1-based | R |
1-based | Julia |
Despite on hot discussions regarding which approach is correct I would say it was historically confirmed that both of them work well.
The 0-based indexes are good because of their native support of pointer arithmetic and their half-open intervals nature. The 1-based indexes have real-life indexing approach (we use the same approach every day), have good support for the processing of vectors and matrices (linear algebra) in the form of arrays.
So, there is no right answer, which approach is better, as always – context does matter.
Note: I know that there is another small set of programming languages (Ada, Pascal) which supports N-based array types when their minimal indexes are fully defined by the programmer. Such behavior is an exceptional case and I decided to omit it in this article.