<p>Everything naturally starts at 0. In the beginning, there was nothing. Now, there is all.</p>

<p>You might want to know if you have something or not, and how many as well. It's just easier to say how many.</p>

<p>Also, try counting without 0.<br/>
1, 2, 3, 4, 5, 6, 7, 8, 9
That's only 9 numbers. But if you count 10-19, you have 10 different numbers. 10-20, you have 11. It's easier to just go by the 10s place and group the numbers in tens.</p>

CC BY-SA 4.0
2020-05-13T22:51:32.937Z
2020-05-14T12:07:07.290Z
2020-05-14T12:07:07.290Z
ColeDassWest
<p>There are many answers but I miss an attempt to make it short and comprehensible for non programmers.</p>

<blockquote>
  <p>I don't really want to be explaining memory addresses to a new programmer who doesn't understand memory layout and maybe doesn't even understand arrays yet.</p>
</blockquote>

<p>A simple and short example.<br>
We have a list of elements aligned one after the other. The start of this list, the first element is flagged with a pin.<br>
To get the first element, we go to where the pin is.<br>
To get the second element, we need to go to the pin <strong>plus one</strong> element.<br>
Starting at zero the computer can simply calculate where to go from the start location.</p>

<p>More thoughts on that.<br>
Counting starts with "one" for the first element. Even for programmers. But programmers <strong>don't count</strong> elements when they start at zero, they <strong>give them names</strong>. These names start at the first number that can be built with digits. Zero denotes "nothing" but is the first valid number.</p>

<blockquote>
  <p>couldn't a modern compiler often optimize this away?</p>
</blockquote>

<p>I think it can't. How? The calculation described above is fundamental, the CPU does it like that. A compiler can't optimize necessary calculations away.</p>

CC BY-SA 4.0
2018-09-13T10:55:05.300Z
Of course a compiler could optimize this away - this was very common on x86, for example, because of its powerful memory addressing; especially since 486 and Pentium. And of course, just have a look at any modern disassembled code - in most cases, you will not find any direct indexing from the base of the array anyway. Ultimately, in many cases, indexing an array is a relic anyway - for most cases where you see indexing, what you really want is iteration. It's just that many programmers and languages are stuck without distinction between the two.
Luaan
CC BY-SA 4.0
2018-09-13T11:07:29.373Z
C or many other languages don't have iteration so we really should know what it is and how it works. Modern techniques sometimes are great but sometimes they are simply overcomplicated, less comprehensive compared to [i] and I don't think there is no kind of index accessing behind iterators - we just don't see it any more. So I doubt iterators are really faster than a simple [i].
puck
CC BY-SA 4.0
2018-09-13T17:00:23.073Z
C was deficient in that regard even in comparison with other languages *of its time*. And no, they're certainly not *less* comprehensive. You need to look at code with fresh eyes - a lot of the crazy doesn't seem crazy anymore when you get used to it. The thing about iterators is that any indexing is strictly an implementation detail - which allows you to give much more freedom to the code that's using them as an interface. If you pass an array, it will always be an array. If you pass an iterable, the implementation can do whatever fits - like using a linked list.
Luaan
CC BY-SA 4.0
2018-09-13T17:02:48.893Z
Iterators can easily be faster than pointers, and they can be slower than pointers. But they're definitely easier to understand and reason about, and they allow a lot of optimisations that simply aren't possible with "pointers to an array". Just consider something like map-reduce - it wouldn't be possible if people stuck to the idea that arrays are just a pointer to the first item in an array. Unsurprisingly, it came from the other side of the language spectrum - languages that value abstraction over micro-tweaks.
Luaan
CC BY-SA 4.0
2018-09-09T09:22:42.333Z
2018-09-09T09:22:42.333Z
puck
<p>You give the answer yourself in the third bullet point, and you dismiss it too easily.</p>

<p>Let me delve into my personal experience from when I learned C in the mid-1980s. I remember when for the first I time saw 68k assembler code produced from indexing an array in C and realized that variables are just constant addresses, and indices are just offsets to them, so that addressing an array element <code>a[i]</code> could be understood as <code>*(a+i)</code> which simply was a readily available adressing mode in machine code if  address <code>a</code> was already in a register.</p>

<p>It was a revelation on many levels: What C is (a macro assembler with a few bells and whistles plus standard library), what a compiler does, under what constraints programming languages work, and why C was so fast.</p>

<p>Why do you want to deprive your students of this insight? I think teaching arrays (or any programming, really) benefits <em>tremendously</em> from teaching memory addresses and some rudimentary assembler, so just go for it. All language abstraction is operating under the constraints of the metal. Your students will never understand why certain seemingly simple things are expensive or impossible if they <em>don't know what they are actually doing.<sup>1</sup></em></p>

<p>To sum up, essentially your third bullet point is the reason for the decision by the designers of C (or probably rather, BCPL or B) to start indexing at 0. Saving a subtraction at each element access, i.e. in many hot loops, was certainly highly relvant in 1970. True, <em>today</em> these original reasons are largely irrelevant; but today we have 45 years of code and a diverse C-rooted language tree. Regarding these languages we are locked in for good. As Jörg correctly mentioned in another answer, the decision was made differently for many other languages, probably not coincidentally some for which speed is secondary and some who target a lay audience.
<hr>
<sub><sup>1</sup>Don't get me wrong, I like abstraction. Having had the glimpse under the hood lets me actually appreciate the saftey, correctness and comfort provided by high-level languages and libraries.</sub></p>

CC BY-SA 4.0
2018-09-10T16:16:08.863Z
2018-09-11T00:13:45.583Z
2018-09-11T00:13:45.583Z
Peter - Reinstate Monica
<p>Slight generalization of CJ Denis's answer: The advantage of zero-based indexing is apparent as soon as you start working with relative indices. If you have a base array A and over it, let's say, a sliding window W, you would have to subtract 1 each time you add W-based index to the A-based one.</p>

CC BY-SA 4.0
2018-09-18T11:20:50.850Z
And if I add your SSN to my SSN... how does that translate to the array? Indices are a different level of abstraction than "there's 20 bytes after this pointer that represent an array of `short`s". You can argue that (e.g.) C chose this way of representing arrays an indices because of performance targets, but that's about all you can argue about that. A lot of the problems in software engineering stem from this way of thinking that just because it's possible to add two numbers together, it makes sense. It may have it's place in the lowest levels of our systems, but not normal application code.
Luaan
CC BY-SA 4.0
2018-09-03T12:00:26.160Z
2018-09-03T12:00:26.160Z
Edheldil
<p>The technical answer, the one where you explain memory, and the base and index register, should be your preferred method of instructing. I understand that some people think it's daunting, but in reality, it is really straight forward, and it should be the first thing you teach about programming. All of the stack overflows, stack underflows, buffer overflows, null pointer exceptions, dangling pointers, memory leaks, etc are all a lot easier to understand if you start with the basics of what a computer actually does. And you don't need to get super-technical with buses and caches and so on, just enough so that when a memory-related problem happens, they will understand why it happened easier. </p>

<p>As a comparison, which do we teach first in math: addition or multiplication? The reason why is because the latter is a concept built upon the foundation of the former. Teaching what a variable is before teaching what memory is akin to teaching multiplication without ever explaining addition. Everything we do in every computer language that exists on the market to today uses registers and memory. All of them. 100%. To completely gloss over the fundamental basics of computing is to perform a serious disservice to those you are supposed to be educating.</p>

<p>I realize that many modern languages have done away with bare pointers because of their potential for misuse, but that means that the new generation of developers are growing up without understanding a critical part of computers. And pointers are still everywhere, just neatly tucked away behind references, objects, automatic variables, and so on. Which leads to questions about in/out parameters, why changing a value here affected data elsewhere, etc.</p>

<p>Until we have a computer that literally has no concept of a stack, registers, heap/dynamic memory, loops, branches, etc, no matter how far we abstract, at some point, the processor needs to do its thing. And that thing will be done by loading a memory address to a base register, loading an index register, and loading the data from memory as a result of the final calculation. If students do not learn this in class, they will certainly not learn it in the real world in any appreciable amount of time, and will write far inferior code for perhaps the rest of their developer career.</p>

<hr>

<p>Teach your students the basics of computers, and I can virtually guarantee that anyone with sufficient aptitude to be a developer to begin with will never ask the question "why do we count from zero." Once the basics are established, everything else becomes that much easier.</p>

CC BY-SA 4.0
2018-09-13T10:55:58.590Z
Variables are entirely separate concept from memory; even today, most of the variables you use never make it into memory. As for pointers... pointers are everywhere, yes. Pointer *arithmetic* is a fetish that should have died ages ago. Multiplication *can* be explained in terms of addition, but it doesn't have to. The reason we teach addition first is because it's easy to teach algebraically, while multiplication makes far more sense geometrically - and it so happens that most math teachers are a lot more comfortable with algebra than geometry. But that's an entirely subjective value.
Luaan
CC BY-SA 4.0
2018-09-12T01:18:45.187Z
2018-09-12T01:18:45.187Z
phyrfox
<p>There are several explanations. But I would say that the main reason is because the number in computer science represents a memory offset i.e. the physical distance from the beginning of the memory.</p>

<p>0 then means "no distance from the beginning of the memory" that is, the start. </p>

CC BY-SA 4.0
2018-09-14T16:53:03.903Z
I 100% agree. When I saw this answer for the 1st time, I was totally convinced. However this is not the first time that this answer has been given, and **some** of the older versions, give deeper explanations.
ctrl-alt-delor
CC BY-SA 4.0
2018-09-11T07:56:52.943Z
2018-09-11T07:56:52.943Z
Niklas Rosencrantz
<p>You are starting with the first element of you index set.</p>

<p>In a math text, your index set usually is $\mathbb{N}\setminus\{0\}$, because this is how you normally count.</p>

<p>But in your PC you use an unsigned integer type as index set. And the <strong>first</strong> element of this ordered set is the number $0$, not the number $1$.</p>

<p>So the problem is your number type. You could have a natural-number datatype without zero for your index and everything would be fine. But we like to re-use existing data types used for arithmetic, which normally need to have a $0$, which comes before the $1$.</p>

CC BY-SA 4.0
2018-09-12T11:47:25.257Z
2018-09-12T11:47:25.257Z
allo
<p>Modern computer implementations (physical, CMOS, as well as most virtual machines) almost completely use only binary logic (although some flash memories may use more than 2 states per physical bit cell).  </p>

<p>By convention, if you have 1 bit of binary information, or a single logic signal, there are two possible states, and we call one state “0” and the other state “1”.  If that 1 bit addresses 2 bits of memory, then the two addresses are 0 and 1 to match the binary state nomenclature of the address bit.  </p>

<p>Early TTL Logic data books labeled the signal state nearest 0 Volts as logic “0” in the truth tables.</p>

<p>Compositions of a small number of logic bits (more than one) are usually numerically interpreted as sums of powers of two times those binary bits, and the minimum unsigned sum is zero.</p>

<p>Many early programming languages (assembly) grew out of shortcuts for data and program entry via binary switches.  The conventions followed.  Lots of binary zeros sum to numeric zero.  And you count up starting from there.</p>

<p>If you are a CS educator, you should not be teaching computation as magic, but as the result of the implementation of comprehendable binary logic.</p>

CC BY-SA 4.0
2022-05-04T04:39:29.503Z
This is merely moving the question to: why is binary using 0/1 and not 1/2
MarcH
CC BY-SA 4.0
2018-09-23T03:32:24.517Z
2018-09-23T04:05:16.820Z
2018-09-23T04:05:16.820Z
hotpaw2
<p>Very simple:  This is the offset of the address.  So if an array called x is <code>located with x at say 0x1000</code>, an array that start's there has its first element <code>x[first] at 0x1000</code>
By using:</p>

<pre><code> 0 as [first]
</code></pre>

<p>there's no math to compute it's start, and it is computationally efficient.</p>

CC BY-SA 4.0
2018-09-14T16:53:50.060Z
I 100% agree. When I saw this answer for the 1st time, I was totally convinced. However this is not the first time that this answer has been given, and some of the older versions, give better explanations.
ctrl-alt-delor
CC BY-SA 4.0
2018-09-14T19:21:01.420Z
As pointed out, other earlier answers mention this, but it is a concise explanation, "in my own words" IMHO.
JosephDoggie
CC BY-SA 4.0
2018-09-12T21:02:50.487Z
2018-09-12T21:02:50.487Z
JosephDoggie
<p>Gypsy Spellweavers answer pretty much nails it, and looking at an index as an offset to a memory address (as JosephDoggie and others suggest) gives a precise technical reason. However, there is something I'd like to add:</p>

<p>It is a great tragedy that we don't "count" from zero in our everyday life. That is because early humans didn't have a concept of <em>zero</em>. That concept was unfortunately introduced much too late. We naturally use a decimal system because of our ten fingers (we also use a base 5 system for stroked lists, with the diagonal stroke representing a thumb). We should actually use a base 11 system, because we can display not ten, but eleven states with our hands: 0 fingers up to 10 fingers up.
So if only the concept of zero had evolved earlier in the history of mankind, "counting" from zero would feel perfectly natural to us (and Matlab wouldn't start indexing at 1).</p>

CC BY-SA 4.0
2018-09-14T16:50:47.850Z
I am not sure that I agree, with all of paragraph 2 (counting from zero), but the base 11 thing is spot on. Why did I never see this. I am going to use base 11 from now on (or at least for a week). Oh no I failed already, I write eleven in base 10. I should have written 10 (that is eleven in base 10). Yes that is what I will do. I will use base 10 from now on.
ctrl-alt-delor
CC BY-SA 4.0
2018-09-13T08:25:51.873Z
2018-09-13T08:25:51.873Z
user82593
<p>We count from 1 because we started counting before the zero was invented.</p>
<p>We should have all switched to the new, lowest digit when it was invented but this habit was impossible to kill so we stuck to 1.</p>
<p>The revolution that came with the zero is called <a href="https://en.wikipedia.org/wiki/Positional_notation" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Positional_notation</a>, also known as &quot;place-value&quot;. Positional notation allowed us to <em>re-use the same digits</em> to count tens, hundreds, thousands, etc. If you pay attention, you'll notice that tens, hundreds and thousands all  start with the new, lowest digit: zero. But for units it was too late; too hard to change.</p>
<p>However many programming languages <em>did</em> the switch and count all digits from zero because keeping units special and different from all other digits creates irregularities and edge cases; see examples at <a href="https://en.wikipedia.org/wiki/Zero-based_numbering#Numerical_properties" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Zero-based_numbering#Numerical_properties</a> and in some of the other answers here.</p>

CC BY-SA 4.0
2022-05-04T22:48:15.677Z
This is a weird and false history.  Counting from 1 still *exists* because it is useful in many contexts. The question you are responding to is about why counting from zero is useful in *this* context.
Ben I.
CC BY-SA 4.0
2022-05-04T23:08:20.053Z
Which exact fact is false @BenI.? You don't say. Counting from zero is useful in any context, Intelpedia gives many examples unrelated to computers.
MarcH
CC BY-SA 4.0
2022-05-05T02:58:41.530Z
The second article you linked to makes one generalized mention of the problems with zero-based numbering, though since it's an article about the benefits, it isn't a surprise that it doesn't speak more to it.  Zero-based counting is excellent for distances (such as arrays) and its analogs, but disallows the ordinal and cardinal count to match.  If you have index zero, you now have one element, and that mismatch is permanent.  And if you have zero elements, then the question of index becomes undefined....
Ben I.
CC BY-SA 4.0
2022-05-05T03:00:09.760Z
... Sometimes we want distance measuring, sometimes we want ordinal and cardinal to match, such as when we are counting eggs in an egg container.  Both systems have their use and their place.
Ben I.
CC BY-SA 4.0
2022-05-05T03:05:19.537Z
You intimate a history in which habit, not clear usefulness, is the reason that standard counting is still around, and it's simply not true.  Every school in the world teaches traditional counting to small children, and children everywhere learn that most people have ten fingers, and learn how to count them so that they *arrive at that number.*  It's a big benefit, and should not be discounted.
Ben I.
CC BY-SA 4.0
2022-05-06T04:37:59.297Z
So you don't think we counted from 1 before zero was invented?
MarcH
CC BY-SA 4.0
2022-05-06T13:13:14.200Z
We did, I don't contend that you are wrong about everything.  The false history is the part where you say that we kept standard counting because of "habit" instead of "usefulness".  Both systems are useful.
Ben I.
CC BY-SA 4.0
2022-06-01T01:16:33.860Z
"Both systems have their use and their place" - you're justifying habit better than I would ever have.
MarcH
CC BY-SA 4.0
2022-06-01T01:36:30.160Z
Even in programming, no programming language has removed the standard count.  It would be nonsensical to use positional notation for the size of an array, and we don't, ever.   When your maximum index is [0] (positional counting), your list size is 1 (standard counting, which also matches the maximum ordinal number).  If we all "switched over" you list size would now be zero if your only position was zero, and you would no longer be answering the question "how many items are in this list", because that is not a positional question.
Ben I.
CC BY-SA 4.0
2022-06-02T02:25:34.410Z
You're very very close. I've never seen someone explaining pure convention so well while falling so short of realizing it's just convention. Fascinating.
MarcH
CC BY-SA 4.0
2022-06-02T02:53:51.800Z
**Person 1:** *holds up an apple* How many apples am I holding?  **Person 2:** Zero.  **Person 1:** *puts down the apple* How many now?  **Person 2:** an undefined number.  If that conversation sounds useful to you, then this conversation probably isn't.
Ben I.
CC BY-SA 4.0
2022-05-04T04:37:46.310Z
2022-05-04T04:37:46.310Z
MarcH
<p>"Thing zero"</p>

<p>I have nothing, I have one thing, I have two things... </p>

<p>0,1,2... </p>

<p>0x00, 0x01, 0x02... </p>

<p>0000, 0001, 0010...</p>

<p>There is nothing in my register, there is one thing in my register, there are two things in my register.</p>

<p>There is nothing in my array, there is one thing in my array, there are two things in my array.</p>

<p>If you started at one, you'd always have a minimum of one thing.</p>

CC BY-SA 4.0
2018-09-08T22:30:11.703Z
But myint[0] isn't nothing, it's something.
Ben I.
CC BY-SA 4.0
2018-09-08T22:15:05.737Z
2018-09-08T22:15:05.737Z
Munkee
<p>It's not an answer, but it is additional information.</p>

<p>When I was a student, what eventually helped it click for me is that I always found it really annoying and weird that the "19th Century" goes from 1800-1899, and the "20th Century" goes from 1900-1999.</p>

<p>But if we would have started indexing centuries at 0, then the "0th Century" goes from 0-99, the "1st Century" goes from 100-199, ... the "19th Century" goes from 1900-1999, and the "20th Century" goes from 2000-2099.</p>

<p>Likewise – if you're in a place where soccer/football is popular – we typically say the "1st minute" to talk about 0:00–0:59, the "27th minute" to talk about 26:00–26:59, etc. Had we started indexing minutes at 0 instead, the "27th minute" would more logically be 27:00–27:59. (Of course, both of these ignore the additional confusion that the 90th minute is sometimes considered to be 89:00–93:00.)</p>

CC BY-SA 4.0
2018-09-11T16:17:15.313Z
Actually, not everyone agrees with your first paragraph. Some count centuries starting with year "1" as in 1901 thru 2000. There was a lot of worry about that at the millennium and the danger that systems would fail at the rollover whenever that was. Also, I'll note that the Western calendar doesn't have a year 0. It jumps from 1BCE to 1CE with no 0 in between. Personally, though, The 17th century, being the sixteen-hundreds has always been a pain for me.
Buffy
CC BY-SA 4.0
2018-09-11T16:36:08.820Z
And then when a student well-actualy's you like that, they fell into your trap and you say, "Wouldn't it make a lot more sense if we started at year 0 and our centuries started at 1900, not 1901? That's 0-indexing." :P
Bryan
CC BY-SA 4.0
2018-09-11T17:13:04.317Z
Hmmm. Well, actually, I was just pointing out an historical fact.
Buffy
CC BY-SA 4.0
2018-09-11T17:43:46.053Z
@Buffy Surely that is now anachronistic? I never heard a peep about that when the year 2000 was rolling around. It seemed clear enough at the time that the popular understanding is that the centuries go from '00-'99.
Ben I.
CC BY-SA 4.0
2018-09-11T17:45:32.833Z
Well, see, https://www.scientificamerican.com/article/when-is-the-beginning-of/
Buffy
CC BY-SA 4.0
2018-09-11T17:50:05.503Z
But the technical issue mostly involved using two bytes for a date's year, so the issue was what happens when 99 becomes 00. The fear was that all date computations would fail and take financial systems (etc.) with them.
Buffy
CC BY-SA 4.0
2018-09-11T17:55:37.740Z
There were other issues with two digit dates, of course. some people on their 100th birthday were suddenly considered infants and their pensions, etc were put on hold along with some other legal problems. I don't know if you are old enough to remember the web in the previous century, but it was common (nearly universal) for a date form to have two digits for year. You entered your birthday as 7/9/88, for example. That has changed now.
Buffy
CC BY-SA 4.0
2018-09-14T17:02:01.107Z
So in a race the person in 0th place is the winner (gets the gold). The 1st place gets silver, and the 2nd place gets bronze.
ctrl-alt-delor
CC BY-SA 4.0
2018-09-11T16:10:01.470Z
2018-09-11T16:10:01.470Z
Bryan
<p>Languages which start from 0 are currently popular but there are others which start from 1.  These examples are quite old.  Many of the start from 0 languages are derived from or inspired by C.  </p>

<p>Cobol is not fashionable now but it is still an important language in business and its arrays start at 1.  RPG (not role playing games) also has arrays which start from 1.  RPG is ugly and horrible but it is also popular in business.  My Fortran is rather rusty but I think that it also started at 1.  Very long ago, I used Algol and you could choose the starting index 0, 1, or even negative.  For some applications, negative indexes e.g. from -10 to +10, were convenient.  I am not sure whether this was a standard feature or just one of the dialect that I used.  Things were not so standardised back then.  </p>

<p>Edited to remove possible unintended offence.  </p>

CC BY-SA 4.0
2018-09-13T10:49:20.133Z
Pascal and Visual Basic (and many other Basics) also preferred natural indices. Using zero-based indexing really has to do with conflating indexing and pointer arithmetic. If I want an array from -10 to 10, why should I index it from 0, right? Let the compiler/library deal with the details. C didn't have indexing at all, *only* pointer arithmetic, so there was little choice. For some weird reason, even today people still count this as C's *advantage*, rather than misfeature. Oh well.
Luaan
CC BY-SA 4.0
2018-09-13T11:39:09.770Z
I considered including Basic but it was so long since I have used it that I was not sure.  Also, as you hint, it is probably dialect dependent.  I miss the ability to choose the minimum and maximum index.  It is a shame that it has not caught on.
badjohn
CC BY-SA 4.0
2018-09-13T17:05:01.083Z
Plenty of languages on the "abstraction makes things easier" side of the barrier still support ranges. You just need to give up C-like languages, for the most part (though e.g. C# does have support for arbitrary indexing, it's not really "equal citizen" compared to zero-based).
Luaan
CC BY-SA 4.0
2018-09-09T12:15:13.877Z
2018-09-10T13:02:24.313Z
2018-09-10T13:02:24.313Z
badjohn
<p>None of the reasons you suggest really get to the heart of why we use zero-indexing in CS. Dijkstra's <a href="https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html" rel="noreferrer">EWD831</a> explains why this convention works out the best. It comes down to the fact that we want to represent sequences of integers as half-open intervals that are inclusive on the start side.</p>

<blockquote>
  <p>To denote the subsequence of natural numbers 2, 3, ..., 12 without the pernicious three dots, four conventions are open to us<br>
  a) 2 ≤ i &lt; 13<br>
  b) 1 &lt; i ≤ 12<br>
  c) 2 ≤ i ≤ 12<br>
  d) 1 &lt; i &lt; 13</p>
</blockquote>

<p>To paraphrase Dijkstra:</p>

<ul>
<li>(a) and (b) have the advantage that subtracting the bounds gives you the length, which is convenient because you don't need to remember to add or subtract 1.</li>
<li>(a) and (c) have the advantage that sequences starting with zero don't need a negative lower bound -- and negatives are no longer natural numbers.</li>
<li>(a) and (d) have the advantage that if you create an interval that starts with zero and shrink it down to zero-length, you don't need a negative for the upper bound.</li>
</ul>

<p>Because of the above, we want to write all of our intervals as (a).</p>

<p>Once you accept that (a) is the correct way of specifying intervals, indexing an array of length N as [0, N) is much nicer than [1, N+1).</p>

<hr>

<p>Two additional notes in favor of using (a) for intervals.</p>

<p>The first point above is important because half-open intervals nicely decompose into other half-open intervals. This makes implementing divide-and-conquer algorithms like merge sort significantly less error prone.</p>

<p>For example:</p>

<ul>
<li>[4, 14) can be broken into the equal-sized intervals [4, 9) and [9, 14), and the middle index is computed as $9 = \frac{4 + 14}{2}$. This is quite clean and nice.</li>
<li>[4, 13], decomposes into [4, 8] and [9, 13], where you get the end of one sequence as $8 = \frac{4 + 13 + 1}{2} - 1$, and the beginning of the next sequence as $9 = \frac{4 + 13 + 1}{2}$. It's easy to forget to add or subtract 1 somewhere.</li>
</ul>

<p>It's also a bit jarring to specify intervals with (b), because it feels unnatural to skip the first element when you're writing a loop.</p>

<hr>

<p>As for how to explain the above to your students, I think that they just need to accept that breaking sequences of integers in half is something they'll do later on, and then a few examples will quickly point to [,) intervals and zero indexing as the most natural choice.</p>

CC BY-SA 4.0
2018-09-03T06:53:37.377Z
The half-intervals decomposing into half-intervals is a nice touch. Dijkstra's explanation does good job of justifying the use of the common scheme within CS as it was becoming a modern science.
Gypsy Spellweaver
CC BY-SA 4.0
2018-09-03T12:11:14.367Z
Nice contribution and good insight. You've made this corner of the internet a better place :) Welcome to [cseducators.se]. Take a look around, I'd love to know what else you can add.
Ben I.
CC BY-SA 4.0
2018-09-04T13:34:16.990Z
While a good reason to start indexing at 0, it feels much easier and more natural to mentally parse (d) and especially (c) than (a) or (b) - "numbers from x to y" in natural language usually means inclusive of both (or exclusive of both)
msam
CC BY-SA 4.0
2018-09-04T16:21:59.273Z
Note that adopting the convention more widely helps in a number of other scenarios, not just array indices.  For instance, it [eliminates a whole class of errors in date handling](https://sqlblog.org/2011/10/19/what-do-between-and-the-devil-have-in-common).  If you're doing something like a fee scale for package weights, the exclusive upper-bound also allows measurement result to be independent of the limit specified (ie - if an inclusive upper bound is given as `2.9` but the scale measures as `2.95` you have issues).
Clockwork-Muse
CC BY-SA 4.0
2018-09-05T01:30:59.653Z
@msam: Fully closed or fully open may be "more natural," but the subtraction property of half-open is extremely important.  The interval [a, a+b) is exactly b elements long, without any pesky +1 or -1 terms.  You simply cannot avoid having +1s and -1s everywhere when you use fully closed or fully open intervals.
Kevin
CC BY-SA 4.0
2018-09-05T01:48:00.613Z
This also matches the behavior of the modulo operator, the return value of which lies in [0, n). `number_of_values_ending_in_a_particular_digit[x % 10] += 1`
Roman Odaisky
CC BY-SA 4.0
2018-09-05T17:14:58.923Z
This is a good reason, but I think a more fundamental one is simply hardware: binary registers and memory locations representing unsigned integers have a 0 "all bits off" state. Indexing by one would waste that.
Lee Daniel Crocker
CC BY-SA 4.0
2018-09-06T12:07:56.493Z
Every answer with Dijkstra in it is nice. But......... this answer seems to answer a completely different question, doesn't it? This answer only concerns itself with the openness of intervalls. Neither the quote from Dijkstra nor the rest of the answer has anything to do at all with the actual question - which is, to rephrase a bit, "why do array indices start at 0" (sic).
AnoE
CC BY-SA 4.0
2018-09-07T00:25:39.607Z
Those reasons don't seem entirely compelling in the argument of 0 vs 1.  For example, in the second point you can argue that sequences starting with 1 don't need negative numbers either, and in the third point, you can argue that sequences starting with 1 also don't use negative numbers for zero-length (although the counter-counter-argument is that they still require reversed bounds, which may be confusing).  And if you know that the lower bound is 1 then the upper bound in form (c) is also the length, no arithmetic required.
Miral
CC BY-SA 4.0
2018-09-07T19:49:03.590Z
Good point about the half-open ranges. The other common  case where these come in useful is string manipulation. Having zero-based half-open ranges there makes substring positions and lengths a lot cleaner to work with.
Dewi Morgan
CC BY-SA 4.0
2018-09-11T14:12:42.540Z
What do you mean by "indexing an array of length N as [0, N)"?
HelloGoodbye
CC BY-SA 4.0
2021-05-18T01:31:05.890Z
"indexing an array of length N as [0, N)" - perhaps I'm not understanding the notation (especially the varied brackets), but surely an array with 0 ... N elements is not of length N?
youcantryreachingme
CC BY-SA 4.0
2018-09-03T06:34:31.090Z
2018-09-03T06:34:31.090Z
drawoc
<p>If I can modify the question, I can answer what I believe you are looking for.</p>

<hr>

<p>The question is "Why do we count starting from zero?" The answer is "we don't" Not even in computer science do we "count" from zero. A list with 15 items in it from outside CS still has 15 items in it inside CS realms. Many languages include a <code>count</code> type function for arrays, and such a function would still return 15 for that list.</p>

<hr>

<p>If the question becomes "Why do we <em>index</em> from zero?" then it has a different answer. This time the answer is "because that's the way everyone else does it." When we separate the concepts of "indexing" and "counting" things become simpler to explain. Often true of any concept, use the proper terminology and many difficulties are eliminated.</p>

<hr>

<p>As to why we, as humans, index from zero, while counting from one, only requires a little thought before clarity arrives. Assuming a classroom environment, where the class period lasts for a specified time, perhaps 50 minutes, you can ask at very near, but after, a 60 second mark, how many minutes the class has been in session. If asked at 5:02 minutes into class, the answer will be five minutes. Ask them how long class had been in session five minutes ago, which would be around 0:20 into the class period. The answer should be zero minutes. Once they accept that it was zero minutes, even at 0:59 into the class, you can emphasize that even though the class time had not reached a full minute, it <em>is</em> still class time, and should have some way of "indexing" it. Since the number before one is zero, it must have an index of zero. Hence the "first minute" (by counting) has an index of zero.</p>

<p>The same thought experiments can be conducted with a ruler/tape measure, where the measure starts at zero, and the first centimeter/inch is called, and written, zero. The same concept applies to any distance, such as miles or kilometers, but those are harder to fit into the classroom. In the USA, most highways have "mile markers" that help in locating people for emergency responders. They mark the distance from the beginning of that highway on its south-western end. (The beginning is at the state line if it crosses from one state to another.) "Mile marker" 1 is set after the first mile is completed. "Mile marker" 0 is sometimes seen on the state line, though it is not always there. The first mile, in counting, has an index of 0.</p>

<p>As another example, though not quite as helpful, and requiring that the students have a level of algebra experience to apprehend it, is exponents. Limiting it to non-negative powers of ten and applying it to whole numbers only, we can use the fact that $10^0 = 1$ while $10^1 = 10$. The exponent represents the index for how many places to the right to move (again distance <em>to move</em>) the decimal point, while the <em>count</em> of the digits before the decimal point will be 1 larger. </p>

<p>Final demonstration: "What is the <em>index</em> of the first position on the volume knob below?" "What is the <em>index</em> of the last position on that volume knob?" "How many positions can you <em>count</em> on that volume knob?"</p>

<p><img src="https://i.sstatic.net/dzHYQ.jpg" alt="Volume Knob"></p>

<hr>

<p>Once the "index" vs "count" is solved, you can move into the CS realm, where the same practices are followed.</p>

<p>An array is "indexed" from zero and "counted" from one. Why? Because that is the way humans index and count. It certainly comes in handy when doing arithmetic with memory addresses, and there's nothing wrong with taking advantage of things that "just work" naturally. Similar shortcuts include dividing and multiplying by powers of two by shifting bits to the right of left. Its usefulness to the compiler, or the developer, however, is not the <em>why</em>. Such "benefits" are only side effects of "what was" before CS was a reality.</p>

<p>Bottom line is that index from zero and count from one existed a <em>very long</em> time before electronic computers were invented. Like any other science, computer science has to build upon what already exists before inventing new things. Zero-based indexing is one such "pre-existing" thing.</p>

CC BY-SA 4.0
2018-09-11T17:54:32.510Z
Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/83029/discussion-on-answer-by-gypsy-spellweaver-why-do-we-count-starting-from-zero).
Ben I.
CC BY-SA 4.0
2018-09-19T14:18:14.347Z
"*If asked at **5:02** minutes into class, the answer will be five minutes. Ask them how long class had been in session five minutes ago, which would be around **0:20** into the class period.*" Can't tell if you're assuming it takes 18 seconds, give or take, to answer the first & ask the second question or if it's a typo. ;^)
ruffin
CC BY-SA 4.0
2018-09-19T15:44:26.730Z
@ruffin 18 seconds is an estimate of the dialog time.
Gypsy Spellweaver
CC BY-SA 4.0
2021-05-18T01:36:38.320Z
You are correlating continuous time with discrete "buckets" for storing things - completely irrelevant. To counter, I could say "in which minute are we when we are 0:20 into the class?" and the answer would be "the 1st". So why not index from 1? As for your volume knob, I would assume zero to mean zero volume - that would be an empty array; an array with zero elements. That does not mean the 1st element should be called element zero. Completely irrelevant and I can't believe this got 100+ votes.
youcantryreachingme
CC BY-SA 4.0
2021-05-18T02:42:21.257Z
@youcantryreachingme "How old is the child?" and "Which year is the child in?" also differ by one. It depends on teh question asked. "How many elements in the array?" and "What's the last index of the array?" differ by one. Interestingly enough, if you've used elementary school graphing, zero is also the beginning of each axis, known as the "origin." That difference between "count" and "index" is included in the opening of the answer. Of course, if you find this answer to not be helpful, for any reason, or none at all, you can still down-vote it.
Gypsy Spellweaver
CC BY-SA 4.0
2021-05-18T23:43:06.483Z
@GypsySpellweaver - again - continuous time and continuous axes - irrelevant. The correct answer is Buffy's. See also my "TLDR" comment there. Let's not clog up these comments further by going back and forth.
youcantryreachingme
CC BY-SA 4.0
2022-05-11T16:35:34.393Z
Great answer. You could have mentioned the concepts of "ordinal" vs "cardinal" for "index" & "count". Together with the answer that quotes Dijkstra, this is pretty much it.
Victor Eijkhout
CC BY-SA 4.0
2018-09-03T04:00:13.283Z
2018-09-13T00:02:27.287Z
2018-09-13T00:02:27.287Z
Gypsy Spellweaver
<p>I'm surprised that the following hasn't been stated yet. All of the answers given so far seem to be "after the fact" explanations of something that is really based on the way people built most (not all) early computers as binary machines. </p>

<p>To make things a bit more compact here, I'll assume we are creating a 4 bit (nibble) based machine. We don't want to use more binary components to build a nibble than we need to because we are cheap, so we use four bi-stable components (relays, vacuum tubes, transistors). We think of (perhaps) the two states as zero and one rather than, say, red and green. </p>

<p>So we have (0000) through (1111) as the combinations of the four transistors of a nibble. We can interpret them any way that we like. Suppose we want to interpret them as integers. How shall we assign the different codes to integers. We <em>could</em> let (0000) represent 42, a fundamental universal constant, and (0001) represent 3, an approximation to pi and so on, but we realize pretty soon that any computations we want to do with such an encoding would be pretty complex - and complexity in a machine costs money. We are cheap, remember. </p>

<p>So we notice that the codings are actually binary numbers. Well almost nobody used binary numbers before this so we start to think about it seriously now, as they have an application. I note that some early computers were actually decimal, not binary, but they recognized that while convenient it wasn't cheap. </p>

<p>Now, using binary numbers, not just binary encoding, it becomes "obvious" that the codes represent zero through fifteen, not one through sixteen. Using (0000) to represent 1 just seems dumb at this level - and at this time. </p>

<p>Now, (bit later) we want to index an "array" of nibbles. How shall we do it. Well we assign index numbers to the individual cells. Suppose we have four such cells. How shall we do it? We <em>could</em> use (0001) through (0100) to index them (1 through 4), but now (a-ha) if we have <strong>sixteen</strong> nibbles to index but start with one we can only get (our count) to fifteen without using another nibble or letting (0000) represent the last (sixteenth) cell. That seems dumb, so we (a-ha) index from zero. Now we can index sixteen cells with sixteen codes and it is cheap and <em>pretty natural</em>. The only cost is a bit of confusion in the minds of beginning programmers, but others will pay those costs and our machines can be cheap. </p>

<p>No contest. Index from zero. </p>

<p>The other answers here explore why the arithmetic inside the machine is cheap this way, so I won't repeat it here. But note that all of this happened before any languages at all were invented other than the simplest of machine coding without any abstraction facilities at all. It was just economics and engineering. Make it simple, keep it cheap. </p>

CC BY-SA 4.0
2018-09-03T11:46:22.797Z
Give your students this simple task and they will find the answer themselves: **Number these ten students, each with a unique number, but you can only use a single digit** - they will quickly come up with the solution to number then 0 to 9 - and that is why we index starting at zero, we don't like waste :-)
Falco
CC BY-SA 4.0
2018-09-03T14:51:44.770Z
Interestingly, all the *early* languages have *one*-based (or *user-defined*) indexing (e.g. Fortran (1957), Algol (1958)), or don't have a notion of "array" at all (Lisp (1957)). Zero-based indexing is a rather *modern* invention.
Jörg W Mittag
CC BY-SA 4.0
2018-09-03T17:36:39.273Z
Interesting that on rotary telephones 0 (with ten pulses) comes after 9, but then pulsing the line zero times doesn't really work physically.
Scott Rowe
CC BY-SA 4.0
2018-09-04T00:01:16.903Z
@JörgWMittag: Interesting!  I wonder if designers of early languages were thinking that anyone who knew how computers and binary numbers really worked would just write in assembly language.  Early computers were slow, and early compilers presumably didn't optimize well / at all.  Anyway, this answer is exactly what occurred to me, too: letting an N-bit index address a full 2^N elements.  Power-of-2 buffer/object sizes are a big deal.
Peter Cordes
CC BY-SA 4.0
2018-09-04T00:08:07.377Z
@PeterCordes, languages have been a search for higher levels of abstraction and the ability to write more complex programs without getting lost in the details of assembler. The assumption was that problems were outgrowing our ability to think about them in low level terms. Languages aren't a placebo for babies, but a tool for experts. For a shock, look at the Google home page. Then use your browser to look at the actual source for that. Now try to duplicate it in assembler. Note that even assembler is a language with _minimal_ abstraction, unlike machine code with none at all.
Buffy
CC BY-SA 4.0
2018-09-04T00:15:51.437Z
@Buffy: Yes, I understand that's the other motivation for higher-level languages, and why I use `bash` as a shell instead of an interactive assembler where I'd type `mov eax, __NR_fork` / `syscall`.  But I thought 1958 was still early enough in the history of computing that performance might still trump everything for many problems.  I could easily be wrong. 
 Having grown up with C (and assembly), 1-based indexing seems totally unnecessary and unnatural *to me*.  I'm not familiar enough with the history of computing and the motivations of early language architects to rule out my guess.
Peter Cordes
CC BY-SA 4.0
2018-09-04T08:09:54.807Z
@ScottRowe zero had 11 pulses, and one had 2 pulses. This was to stop the equipment reacting to random single pulses.
ctrl-alt-delor
CC BY-SA 4.0
2018-09-05T08:59:01.297Z
@PeterCordes It's one of the reasons so many computer scientists/engineers hated C and Unix - they took the "performance is better than correctness" approach, which was contrary to the prevailing thought "as computer software gets more complex, it's even *more* important to keep things correct". A correct program that's easy to understand gives you more opportunities for performance improvements too - most of the time when a C program was faster it did so by sacrificing correctness (e.g. ignoring boundary conditions). Dijkstra's lessons on sustainability and quality of software are great intro
Luaan
CC BY-SA 4.0
2018-09-05T09:10:20.987Z
@Luaan: I'm not familiar with early C or Unix being unpopular for that reason. Early compilers sucked at optimization, so to make things fast people left out safety checks?  These days optimizing compilers can hoist bounds-checks out of loops if it's the same bounds on every iteration, so you can write safer code (especially with C++ to hide the noise behind `std::vector`).  C makes correctness optional, and makes you do it yourself, but it's still possible to write correct C functions / programs.  These days it's a nice language for writing hot loops, but not great for maintainability.
Peter Cordes
CC BY-SA 4.0
2018-09-05T09:12:33.157Z
@Luaan: Anyway, I don't see what zero-indexing has to do with correctness in any given language.  zero-indexing isn't *why* C makes unsafe code more easily possible.  Correlation / causation?
Peter Cordes
CC BY-SA 4.0
2018-09-05T13:18:38.540Z
@PeterCordes You need to compare early C with languages of the time - C lacked pretty much all the things that other languages used to help you write correct programs. The goal in C was simplicity on the compiler and potentially performance, the trade-off was effort on part of the programmer. Contrast the difference between, say, iterating over an array in a for loop and doing a `map` - in the first case, you've opened yourself to potential incorrectness (out-of-bounds etc.), in the second these don't even make sense. C's design went directly against what those people thought was good design.
Luaan
CC BY-SA 4.0
2018-09-05T13:25:11.927Z
@Luaan, don't lose track of the fact that C excelled at the task it was actually designed for. Kernighan and Ritchie were, at the time, at Bell Labs looking for a Better Assembler for a "spare" DEC PDP-7 computer they were using to develop Unix. It has the features it has precisely to match instructions in the PDP assembler set. That it was used for other purposes is a fact of history, of course, but for its designed usage it was near ideal. Ritchie wasn't trying to outdo Algol (or COBOL, of course), just do assembler more effectively.
Buffy
CC BY-SA 4.0
2018-09-05T13:34:01.770Z
@Luaan, however, don't conclude from the above that I think C is a _good_ or even _adequate_ solution for modern programming. I would use it if I were writing device drivers and such, but prefer a safer language with  features such as those described by user Peter Cordes. Even safe auto-typing is a big win. Actually safe anything is a big win, especially memory management.
Buffy
CC BY-SA 4.0
2018-09-05T15:06:02.510Z
@ctrl-alt-delor - That's certainly not the case for British lines, and wikipedia suggests it wasn't the common system (https://en.wikipedia.org/wiki/Pulse_dialing).  We used to have fun by dialing people's numbers by hitting the hangup button the appropriate number of times.  Well, maybe "fun" is pushing it.
Guy G
CC BY-SA 4.0
2018-09-05T15:21:19.617Z
@Guyg I did it to defeat the lock (in England), and I had to add one to each number to get it to work.
ctrl-alt-delor
CC BY-SA 4.0
2018-09-05T15:29:52.410Z
@ctrl-alt-delor - I could swear I used to use 1 for 1, 2 for 2, etc, then 10 for zero (also in England).  Some quick Googling seems to confirm this, but I'm happy to be corrected...
Guy G
CC BY-SA 4.0
2018-09-05T15:34:41.053Z
@guyg I just tried it, it seems that you are correct. I wonder where I got that idea from.
ctrl-alt-delor
CC BY-SA 4.0
2018-09-05T16:54:39.030Z
@JörgWMittag yes but the thing that was established before arrays/indeces was that numbers themselves start at 0 in binary.  Because numbers start at 0 it is most natural for indexing to start at 0.
levininja
CC BY-SA 4.0
2018-09-09T09:25:28.193Z
@JörgWMittag "*Zero-based indexing is a rather modern invention.*"  It's been around since the first assembler.
RonJohn
CC BY-SA 4.0
2018-09-10T02:07:25.790Z
@ctrl-alt-delor IIRC the pulses are when you *lift* the button. There's 1 *pulse* for 1, but you have to press it down first.
Will Crawford
CC BY-SA 4.0
2018-09-13T10:51:37.720Z
@PeterCordes Early computers didn't have assemblers, programs were written in machine language directly.
Willtech
CC BY-SA 4.0
2018-09-13T10:52:20.257Z
This answer addresses the question as I understood it.
Willtech
CC BY-SA 4.0
2018-09-13T17:23:11.137Z
@Willtech: Wasn't assembly well-established before higher-level languages came along?  Hmm, maybe not, but same difference in machine code directly: you add an offset to a pointer to get a new address.  (At least on machines that *have* normal address registers for indirect addressing, or memory-indirect addressing)  And/or you have indexed addressing modes.  I don't think any hardware ISAs had 1-based indexed addressing, but I don't actually know really early ISAs.  (I know 8-bit ISAs like 8080 have pointer registers, though.)
Peter Cordes
CC BY-SA 4.0
2018-09-14T23:22:27.140Z
@PeterCordes Direct machine code programming preceded assembly languages, assembly languages were the first higher level languages. Machine code vs assembly code: https://stackoverflow.com/questions/466790/assembly-code-vs-machine-code-vs-object-code
Willtech
CC BY-SA 4.0
2018-09-14T23:35:09.243Z
@Willtech: yes, I know that.  I have a gold badge in the `[assembly]` tag over on SO.  My point was that normal hardware has 0-based indexing / pointer-math, whether you generate machine-code from asm or write the machine code directly.  And my other point was to acknowledge that maybe I should have said "machine code" instead of "assembly" when talking about alternatives to higher-level languages like Fortran, if asm wasn't already widespread before higher-level languages were first being developed.
Peter Cordes
CC BY-SA 4.0
2021-05-18T01:39:34.287Z
TLDR: 0 is the 1st binary number of relevance to electronics and computing and therefore when talking about sets of binary numbers, we use that valuable precious resource of the zero value in the limited binary number set available when computing was being invented. *This* is the most sensible answer. Because the code will need to *match* a binary 0000 when referencing the 1st element of a set. Kudos.
youcantryreachingme
CC BY-SA 4.0
2018-09-03T11:05:53.773Z
2018-09-03T11:45:58.140Z
2018-09-03T11:45:58.140Z
Buffy
<blockquote>
  <p>In computer science, we usually count starting from 0.</p>
</blockquote>

<p>In <strong>programming</strong> or in <strong>(theoretical) computer science</strong>?</p>

<p><strong>In Programming</strong></p>

<p>In C programming language you count from 0 to (N-1). And of course in languages which are influenced by C: Java, JavaScript, PHP, C#, C++...</p>

<p>You already named the reason for this:</p>

<blockquote>
  <p>In C, we can use <code>*a</code> to access the first element of array <code>a</code>.</p>
</blockquote>

<p>... and because <code>a[i]</code> is the same as <code>*(a+i)</code> the first index of the array must have the index 0.</p>

<blockquote>
  <p>This doesn't seem very relevant today for a new student who isn't programming in C.</p>
</blockquote>

<p>In many (most?) other programming languages (Basic, Pascal and Matlab for example) you typically count from 1 to N, not from 0 to (N-1).</p>

<p>(For example in <code>for</code> loops.)</p>

<p>As already said in the other answers there often is the possibility to define the index of the first element of an array freely (e.g. in Pascal) or the index of the first element is even fixed to 1 (e.g. in Matlab).</p>

<p>These languages don't have pointer arithmetic.</p>

<p><strong>In (theoretical) computer science</strong></p>

<p>I have no idea if they count from 0 there.</p>

<p>However I think that the programming languages which are used most influence the way of thinking in theoretical computer science, too.</p>

CC BY-SA 4.0
2018-09-04T00:04:28.720Z
I think the C equivalence of `arr[i]` = `*(arr+i)` follows from its choice of zero-based indexing, not the other way around.  But good point that having pointer arithmetic at all makes zero-based indexing much more natural, and that most still-used languages with 1-based indexing don't have that.  C started as a portable assembly language, so it's totally natural that it works like asm in this regard.
Peter Cordes
CC BY-SA 4.0
2018-09-04T05:53:55.767Z
@PeterCordes I'm not sure. But I think the fact that the array operator can be used for pointer arithmetic at all (such as `ptr[-5]`) played a role in defining that `ptr[i]` is equal to `*(ptr+i)`.
Martin Rosenau
CC BY-SA 4.0
2018-09-04T18:13:01.297Z
The advantage of zero-based indexing becomes even more apparent when you need to map a 2D matrix to a linear array.
200_success
CC BY-SA 4.0
2018-09-06T14:37:01.560Z
This is the missing half of Jorg's answer, which together make the **correct** answer. C made the choice to only support indexing arrays from 0, and after it became popular it influenced the design of a lot of other languages. However, its quite likely *most* languages don't force a 0-based index, and some people thinking this is a computer language thing, (or worse yet, a Computer Science thing) is nothing more than myopia.
T.E.D.
CC BY-SA 4.0
2018-09-10T22:53:19.363Z
Most index from 0, including BASIC (though I'm sure there's a variant which starts at 1). [Here's a table](https://www.wikiwand.com/en/Comparison_of_programming_languages_(array)#/Array_system_cross-reference_list).
Schwern
CC BY-SA 4.0
2018-09-11T05:16:18.010Z
@Schwern Depending on the variant of BASIC arrays start with 0 or 1. However it was typical to start `FOR` loops at 1, not at 0! I just looked into the Acorn Electron manual: Even in BBC Basic (where arrays always started at 0) `FOR` loops were typically starting at 1.
Martin Rosenau
CC BY-SA 4.0
2018-09-13T10:26:34.747Z
@200_success Not really - that's just an entirely *separate* advantage of zero-based indexing. And rarely needs to be explicit in the external interface anyway - that's just again going back to C's pointer arithmetic fetish. How structures are laid out in memory shouldn't be used to design how they're supposed to be used. If you have code-level abstraction, what's the difference between `matrix[0, 0]` and `matrix[1, 1]`? How does it affect your use of `matrix.ToLinear()`? The interface should be meaningful on its own, separate of its concrete implementation.
Luaan
CC BY-SA 4.0
2018-09-03T10:56:56.210Z
2018-09-03T11:04:31.880Z
2018-09-03T11:04:31.880Z
Martin Rosenau
<p>In languages such as C, the first item in an array has an offset of zero from the pointer. If the size of your objects are 4 bytes, the next item has an offset of 1 x 4 bytes.</p>

<pre><code>Index   Size    Offset
0       4       base + 0
1       4       base + 4
2       4       base + 8
3       4       base + 12
</code></pre>

<p>And so on.</p>

<p>If the items were indexed on natural counting, there would have to be an adjustment made by both the computer and the programmer to find the location of the item in memory. Mistakes would be made by having this additional step, particularly on the human side of the process. It's easier, although slightly unintuitive, to use zero-based indexing.</p>

CC BY-SA 4.0
2018-09-03T12:16:47.047Z
Welcome to [cseducators.se]! Isn't this just a restatement of OP's third bullet?
Ben I.
CC BY-SA 4.0
2018-09-03T12:17:57.977Z
yes, the pointer (which is the array) contains the 1st element, then you add 1 to get the next element etc. In assembler we were taught indexing to access arrays, so moving to C it all made simple sense.
WendyG
CC BY-SA 4.0
2018-09-03T12:20:59.200Z
@BenI. My answer addresses the human side of "making it easy".
CJ Dennis
CC BY-SA 4.0
2018-09-04T07:58:52.110Z
Welcome to the community, please read the question. The OP states in the question that this explanation is unsatisfactory, for the intended audience.
ctrl-alt-delor
CC BY-SA 4.0
2018-09-05T09:05:23.960Z
Keep in mind that C arrays are rather plain. In many languages, the pointer refers not to the first item, but to things such as the length of the array. And yet both 0-indexed and 1-indexed arrays exist. Indeed, you could use your argument to argue that arrays should start at 1, because that would allow you to store metadata in the "0 offset".
Luaan
CC BY-SA 4.0
2018-09-06T23:43:02.667Z
@Luaan If the metadata is at "0 offset" there's no guarantee it's the same number of bytes as each entry. In reality, it's a packed format: `metadata` + N x `array-item`. Only the `array-item`s are guaranteed to each be the same size. The array part is still 0 based.
CJ Dennis
CC BY-SA 4.0
2018-09-13T10:18:34.287Z
@CJDennis As surprising as it might sound, plenty of languages older than C didn't have this problem at all - e.g. all arrays had the same element size. C became somewhat famous for encouraging these kinds of hardware-specific optimizations (of course, how effective these turned out to be depended entirely on the programmer). Many considered this to be a step back - instruction-by-instruction performance wasn't thought as an end goal in itself. But regardless, this doesn't change that as soon as you need an offset anyway, 0-based arrays are no longer easier to index than 1-based.
Luaan
CC BY-SA 4.0
2018-09-03T07:12:27.060Z
2018-09-03T07:12:27.060Z
CJ Dennis
<p>You have already gotten several good answers about why zero-based indexing is useful, and you have been explained the difference between indexing and counting.</p>

<p>I now want to challenge the basic premise of your question: it is <em>not</em>, in fact, universally agreed-upon that indexing starts at zero.</p>

<p>In Excel, which is arguably the most widely-used programming language in the world (even though it doesn't look much like a "traditional" programming language), row-indexing starts at <code>1</code> and not <code>0</code>, and column-indexing starts at <code>A</code> and not <code>ε</code>.</p>

<p>In Visual Basic, the programmer can choose between zero-based and one-based indexing as the default indexing on a per-module (per-file) basis with the <code>Option Base</code> declaration. Plus, the programmer can declare the exact index range for each individual array using the <code>To</code> keyword in the array declaration, e.g.:</p>

<pre class="lang-visual-basic prettyprint-override"><code>Dim Count(100 to 500) as Integer
</code></pre>

<p>This declares an array of integers named <code>Count</code> with indices ranging from <code>100</code> to <code>500</code> (inclusive).</p>

<p>In the "Wirthian languages", i.e. Pascal and all its successors (Modula-2, Oberon, Component Pascal), arrays can be indexed by any arbitrary range of scalars (except reals).</p>

<pre class="lang-pascal prettyprint-override"><code>type
   foo = array[-10 .. 10] of real;
   (* an array of reals with indices ranging from -10 to +10 *)

   bar = array['b' .. 'g'] of 100..200;
   (* an array of integers from 100 to 200 with indices ranging from 'b' to 'g' *)

   weekday = (monday, tuesday, wednesday, thursday, friday, saturday, sunday);
   baz = array[tuesday..friday] of boolean;
   (* an array of booleans with indices ranging from tuesday to friday *)
</code></pre>

<p>The Wirthian languages, in turn, inherited this from ALGOL-60 and ALGOL-68.</p>

<p>Ada is similar, <em>any</em> discrete type can be used as the index type. Interestingly, <em>idiomatic</em> Ada style suggests using a range starting from <code>1</code> and not <code>0</code> when using an integer range as indices.</p>

<p>In Eiffel, which is heavily inspired by Wirthian languages, array indices have explicit lower and upper bounds which can be any signed 32-bit integer, so you could have an array with indices ranging from <code>-1000000</code> to <code>-1</code>, for example.</p>

<p>In Fortran, the default is to start at <code>1</code>, but like ALGOL, Pascal, Eiffel, and VB, you can specify any arbitrary lower and upper bound.</p>

<p>In Matlab, indexing starts at <code>1</code>. In APL and Perl, you can choose.</p>

<p>Even in the "real world", there are different schemes. E.g., in Germany, the ground floor, i.e. the floor you enter from street level is called "ground floor", and is usually labelled 0 on elevator buttons that use numbers ("EG" if using letters). The floors above ground level are called "1st upper floor" (and so on) and labelled 1, 2, etc. (or "OG 1", …) The floors below ground level are called "1st lower floor" (and so on) and numbered -1, -2, etc. (or "UG 1", …)</p>

<p>In the US, "1st floor" is the floor at ground level.</p>

<p>Apparently, in Barcelona, there is a "ground floor", a "primary floor", and then the "first floor" is <em>two</em> stairs up from ground level.</p>

<p>There is an interesting discussion about this on <a href="http://wiki.c2.com/" rel="noreferrer">the Wiki</a>: <a href="http://wiki.c2.com/?ZeroAndOneBasedIndexes" rel="noreferrer">http://wiki.c2.com/?ZeroAndOneBasedIndexes</a></p>

<p>I also found an essay that compares the syntactic and semantic noise of typical tasks using many different indexing schemes: <a href="http://enchantia.com/graphapp/doc/tech/arrays1.html" rel="noreferrer">http://enchantia.com/graphapp/doc/tech/arrays1.html</a></p>

CC BY-SA 4.0
2018-09-03T17:41:29.540Z
It would seem that in Barcelona the "first floor" is one floor above the "primary floor", which name suggest that it is the "origin" for the building's life. The "ground floor" is presumably where garage, storage, utilities, and other facilities exist while regular rooms (kitchen etc.) are on the primary floor. Servants' quarters, are also likely to be "below" the primary floor. The ground floor would, presumably, have an index of -1.
Gypsy Spellweaver
CC BY-SA 4.0
2018-09-04T08:19:36.933Z
In one university I have visited, the floor numbers were in feet above sea level. So not even consecutive. (This is also discussed here https://cseducators.stackexchange.com/a/215/204 )
ctrl-alt-delor
CC BY-SA 4.0
2018-09-04T12:20:14.587Z
The reason for the numbering of floors in Barcelona is due to an old building regulation which dictated no buildings could have more than six floors. To work around this restriction, extra floor names were added so that the maximum numbered floor was always #6. The extra floor names are "Entresuelo" and "Principal" just above the ground floor, and "Atico" and "Sobreatico" just above the sixth floor. (Not all buildings will have all of these floor names).
Aaron F
CC BY-SA 4.0
2018-09-04T19:55:20.310Z
There's nothing factually incorrect about these examples but it doesn't mean that it's logical.  The first hour of the day on a 12 hour clock starts is 12 (while minutes start at 0) and the second hour starts a 1.  A 24 hour clock starts at 0.  Which makes more sense?
JimmyJames
CC BY-SA 4.0
2018-09-05T15:11:55.077Z
To add a floor counting example, in some parts in Germany counting starts with ground floor ("Erdgeschoss"), then floor 1, in other parts, counting starts with floor 1 at the ground.  (I almost installed a network in the wrong floor).
Philm
CC BY-SA 4.0
2018-09-05T15:13:56.790Z
Next: In Siemens buildings, it is a tradition that the most lower floor gets number 1, so normally the buildings have (at least) one basement so ground level has number 2 in elevators (which is obviously confusing to most guests)- but if the building has more than one basement- it is not easy to know which number has the ground level- not very convenient for guests or imagine fire alarm.
Philm
CC BY-SA 4.0
2018-09-06T02:35:11.237Z
*Nothing* Wirthian is inherited from ALGOL-68.
philipxy
CC BY-SA 4.0
2018-09-06T14:32:56.233Z
+1, but this is only half the answer. The other half is that in the 70's C made the choice to directly support only indexing arrays from 0, as this made the compiler simplest (which was really C's primary design goal). Because C compilers were so simple, they were easy to make and put on any machine, and as a result of this and a few other bits of historical luck, C became super popular. As a result of that, a whole host of other languages took their lead from C.
T.E.D.
CC BY-SA 4.0
2018-09-06T14:50:13.667Z
@Philm: The Wiki discussion I linked to has an even more confusing example. At IBM Rochester, they use the same numbering, but the buildings are so tightly interconnected that they look and feel like *one* building. So, you could walk a couple of meters on the ground floor and pass from floor 2 to floor 3 without even noticing, just because you happened to step from a building that has 1 basement to a building that has 2.
Jörg W Mittag
CC BY-SA 4.0
2018-09-03T09:38:53.990Z
2018-09-03T09:38:53.990Z
Jörg W Mittag
<p>When I've explained this to beginning students, I don't stray far from your third reason, though I agree that the beginning of arrays is early to introduce the concept of memory addresses.  Among other things, that invites about your variable, <code>c</code>, when the only variable they need to worry about is <code>i</code>.</p>
<p>Instead of memory addresses, I talk about distances from the start. I've given a sample below using paper and a pencil as a reference point, though in my classroom I use the whiteboard and hold a marker.  All of the numbers are in little boxes, and together they form a rectangle.</p>
<blockquote>
<p>Look at the list of numbers on the paper. We all know about ordinal numbers, &quot;first&quot;, &quot;second&quot;, &quot;third&quot;, and so forth. But when we program, we actually refer to the list numbers a slightly different way, as 0, 1, and 2. This is called 0-based indexing, and the reasons for it don't matter right now. What matters is that the <strong>first</strong> item on the list is actually item <strong>0</strong>.</p>
<p>Honestly, that's all you need to know to use arrays correctly. But if you want a hint about why we actually do this, you can think about zero-based indexing as the distance from the head of the array.</p>
<p>So, if I'm at the head of the array, how many moves do I have to make to read the first number?  No moves, I'm already there. What about the second number? I make one move to get there.  The fourth number? One, two, three moves.</p>
<p>Beyond the most important fact that we start counting from 0, thinking about it as &quot;moves&quot; is actually a good way to think about array indexes, because <strong>when we come back to this topic later</strong>, you'll see that the distance from the head turns out to be an important concept for understanding a lot of things a computer does.  Don't worry we'll get there soon enough.</p>
<p>So, for now, what is the index for this spot in the array? <em>(I point to a random index, wait for the students to arrive at the answer.)</em> Good, well done.  Now, moving on to ...</p>
</blockquote>

CC BY-SA 4.0
2018-09-03T12:43:07.563Z
'cardinal numbers, "first", "second", "third"'. These are ordinals, not cardinals. Cardinals count amount. Ordinals count order.
Potato44
CC BY-SA 4.0
2018-09-03T14:49:40.103Z
@Potato44 Yes, they are. What an embarrassing error! Thanks for pointing it out, I'll fix it now.
Ben I.
CC BY-SA 4.0
2018-09-03T14:54:34.190Z
Ah, but some of us are willing to say zero-th, also.
Buffy
CC BY-SA 4.0
2018-09-03T03:47:29.267Z
2018-09-03T14:50:05.263Z
2020-06-18T08:36:57.023Z
Ben I.
<p>Rather than answer myself based off my personal preference, as all other posters have done, I would instead like to link the following very in-depth analysis instead:</p>
<ul>
<li><a href="http://enchantia.com/graphapp/doc/tech/arrays1.html" rel="nofollow noreferrer">Arrays Indexed From One</a> by  Loki Patrick</li>
</ul>
<p>The conclusion it comes to, is as follows:</p>
<blockquote>
<p>In conclusion, I set out to prove by usage cases which scheme was better: indexing arrays from zero, or indexing arrays from one. I think the discussion has shown that there is no mathematically strong argument that favours one or the other. Every usage case which asserts one scheme is better than another because that other scheme is more awkward can be countered either by a language syntax which ameliorates the problem, or else can be balanced against some other usage cases in which the first scheme is more awkward than the other it is being compared against. There are many data points, and the analysis is complex, yielding <em>no clear winner</em>.</p>
<p>However, the thing which tips the balance in my mind is <em>historical convention</em> and <em>interoperability issues</em>. There are so many existing applications for <strong>zero-based indexing</strong>, and many existing languages which use it, that interoperability and learnability are biased in favour of that camp in my opinion. It is disheartening that the result of an intellectual discussion should be settled with &quot;that's the way we've always done things&quot; but in this case it seems a justified conclusion.</p>
<p>That being said, I think for certain specialised or high-level languages, I hope there is a place for one-based indexing, because I feel it has been an inadequately explored solution to the job of addressing elements of an array. I hope this essay has shown that there are some inherently good things about these schemes, and I also hope that future discussions of the issue won't unnecessarily conflate indexing from one with including end-points in loops or slices; although related, the two are not the same issue.</p>
</blockquote>
<hr />
<p>My personal preference is 1-based, because in my experience, the +-1s in 0-based indexing tend to pop up more often in high level logic, while 1-based indexing's +-1s tend to pop up in lower-level code where you need to be paying attention anyway that don't pop up as often in high-level code, leading me to commit notably fewer off-by-one bugs in 1-based languages like Lua.</p>

CC BY-SA 4.0
2018-09-12T15:09:01.327Z
Nice first contribution here.  Welcome to [cseducators.se]!
Ben I.
CC BY-SA 4.0
2018-09-12T15:55:07.173Z
@BenI. Thanks! :-) As a fan of 1-based indexing, it really pains me when people speak from their personal preference, and I in particular hate Djikstra's very selective argument. I've been lucky to find the resource I linked a while ago, because it is a much better analysis than anything I could hope to do.
Llamageddon
CC BY-SA 4.0
2018-09-12T13:49:58.990Z
2018-09-12T17:22:43.563Z
2020-06-18T08:36:57.023Z
Llamageddon
<p>I will try to answer, without reference to low-level programming (or any programming language), without mention of history, or much maths.</p>

<p>As already stated in some answers, we do not count from zero (using the value 0 to represent 1, and 1 to represent 2 (Usually)). So what do we do?</p>

<p>We measure from zero. If I give you a ruler, and ask you to measure something, you measure from zero. If I ask you to tell me how far a cell in an array is from the start, then you measure from zero (the first cell is zero from the start: it is at the start), the 2nd cell is 1 from the start. </p>

CC BY-SA 4.0
2018-09-06T00:03:22.583Z
We absolutely count from zero. If you want to count sheep hopping over a fence, you initialize the `sheep_count` variable to 0, not 1.  If no sheep appear, you must report that zero value as the count.
Kaz
CC BY-SA 4.0
2018-09-13T10:38:50.387Z
@Kaz That simply isn't true at all. This should be pretty obvious when you take into account that zero-as-a-number is a rather recent invention compared to natural numbers. People always considered "nothing" as a special case, and it took effort to introduce zero to math in a meaningful way (and at the cost of confusions like division by zero). You may have been *taught* to count from zero, but it certainly isn't natural to humans. If you want to count sheep hopping over a fence, do you initialize `cow_count` to zero first? I hope not :)
Luaan
CC BY-SA 4.0
2018-09-03T22:31:38.753Z
2018-09-06T08:58:00.277Z
2018-09-06T08:58:00.277Z
ctrl-alt-delor
<p>From time to time I have had to do numerical work in MATLAB and the 1-based indexing always stuck out like a sore thumb, so I have a few examples I can provide where 0-based indexing is advantageous.</p>

<h1>Modular access</h1>

<p>This is the simplest example. If you want to "wrap around" an array, the modulus operator works like a charm. (And don't say "what if the modulus operator were defined from 1 to n instead"—that would be mathematically ludicrous.)</p>

<pre><code>str = "This is the song that never ends... "
position = 300
charAtPosition = str[position % (str.length)]
</code></pre>

<p>Real world examples of this might include working with days of the week, generating repeating gradients, creating hash tables, or coming up with a 
predicable item from a small list given a large ID number.</p>

<h1>Distance of zero</h1>

<p>In a lot of algorithms and applications, we need to work with distances. Distances can't be negative—but they can be zero. For example, one might want to count how many occurrences there are of each distance in a data set. Indexing from 0 allows this to be handled more naturally. (Even if distances aren't integers—see below.)</p>

<h1>Discretisation</h1>

<p>Let's say you want to generate a histogram of heights. The first "bucket" is 50cm-70cm. The next is 70-90cm. And so on up to 210cm.</p>

<p>Using zero-based indexing, the code looks like</p>

<pre><code>bucket[floor((height - 50) / 20)] += 1
</code></pre>

<p>With 1-based indexing, it looks like</p>

<pre><code>bucket[ceil((height - 50) / 20)] += 1
  or
bucket[floor((height - 50) / 20) + 1] += 1
</code></pre>

<p>(the two have slightly different semantics). So you can either have a stray "+ 1" or use the ceil function. I believe the floor function is more "natural" than the ceil function since floor(a/b) is the quotient when you divide a by b; for this reason integer division often suffices in such calculations whereas the ceil version would be more complex. Also, if you wanted the buckets in reverse order, this is 0-based indexing:</p>

<pre><code>BUCKETS = (210 - 50) / 20 - 1

#intuitive because BUCKETS - 1 is the highest index
bucket[(BUCKETS - 1) - floor((height - 50) / 20)] += 1
</code></pre>

<p>versus</p>

<pre><code>#not intuitive... what does BUCKETS + 1 represent?
bucket[BUCKETS + 1 - ceil((height - 50) / 20)] += 1
  or
#not intuitive... how come a forwards list needs "+ 1" but
#backwards list doesn't?
bucket[BUCKETS - floor((height - 50) / 20)] += 1
</code></pre>

<h1>Change of Coordinate Systems</h1>

<p>This is related to the above "direction flip". Although I will use a 1 dimensional example, this also applies to 2D and higher dimensional translations, rotations, and scaling.</p>

<p>Let's suppose, for each slot in the top row you want to find find the best fitting slot in the bottom row. (This often occurs when you want to efficiently reduce the quality of some data; image resizing is a 2D version of this).</p>

<p>With 0-based indexing:</p>

<p><a href="https://i.sstatic.net/NKGyx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/NKGyx.png" alt="0-based indexing"></a></p>

<pre><code>#intuitive because the centre of slot[0] is actually at x co-ordinate 0.5
nearest = floor((original + 0.5) / 5 * 7);
</code></pre>

<p>With 1-based indexing:</p>

<p><a href="https://i.sstatic.net/DjYJ3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DjYJ3.png" alt="enter image description here"></a></p>

<pre><code>#Why -0.5? Can you explain? And then we need to "fix" it with a +1
nearest = floor((original - 0.5) / 5 * 7) + 1;
</code></pre>

<h1>Nice Invariants</h1>

<p>In order to prove that programs work correctly, computer scientists use the concept of an "invariant"—a property that is guaranteed to be true at a certain place in the code, no matter the program flow up to that point.</p>

<p>This is not just a theoretical concept. Even if invariants are not explicitly provided, code that has nice invariants tends to be easier to think about and explain to others.</p>

<p>Now, when writing 0-based loops, they often have an invariant that relates a variable to how many items have been processed. E.g.</p>

<pre><code>i = 0

#invariant: i contains the number of characters collected

while not endOfInput() and i &lt; 10:

    # invariant: i contains the number of characters collected

    input[i] = getChar()

    # (invariant temporarily broken)

    i += 1

    #invariant: i contains the number of characters collected

#invariant: i contains the number of characters collected
</code></pre>

<p>There are two basic ways to write the same loop with 1-based indexing:</p>

<pre><code>i = 1
while not endOfInput() and i &lt;= 10:
    input[i] = getChar()
    i += 1
</code></pre>

<p>In this case <code>i</code> does not represent the number of characters collected, so the invariant is a bit messier. (You would have to remember to subtract one later on if you wanted the count.) Here is the other way:</p>

<pre><code>i = 0
while not endOfInput() and i &lt; 10:
    i += 1
    input[i] = getChar()
</code></pre>

<p>Now the invariant holds again so this approach seems preferable, but it seems odd that the initial value of i can't be used as an array index—that we are not "ready to go" straight away and have to fix up <code>i</code> first. I suppose it's initially odd for learners of zero-based languages that, after the loop terminates, the variable is one more than the highest index used, but it all follows from the basic rule of "a list of size i can be indexed from 0 to i-1".</p>

<p>I admit that these arguments may not be very strong. That said, off-by-1 errors are one of the most common types of bug and at least in my experience, starting arrays from 1 needs a whole lot more adding and subtracting 1 than 0-based arrays.</p>

CC BY-SA 4.0
2018-09-13T10:34:20.710Z
You're blinded by what you're used to. `for` loops are looping from `a` to `b`. *Count* is entirely irrelevant! Pascal made this much more explicit in its own loop structures - `for i := 1 to 10` makes this rather obvious. As far as I'm concerned, your code assumes that one variable contains *two* separate meanings that happen to coincide. That's *wrong*; it may be useful for some cases, but you're reusing the same variable to mean two different things. `i` doesn't contain the count because that's it's purpose - it contains it by accident. The same with your buckets example.
Luaan
CC BY-SA 4.0
2018-09-13T21:55:14.113Z
@Luaan That's the whole point of my post! The multiple meanings don't "happen" to coincide; they are mathematically related, and it is much easier to think about and check for errors if this relation is equal rather than off-by-one. I will admit there are a lot of times where I need to convert array indices to a "1-to-n" system—but almost all of these are to pretty-print things for humans. That is an important consideration—after all, we generally write programs using decimal not hex—however it is also important that code is as easy as possible to review for bugs.
Artelius
CC BY-SA 4.0
2018-09-07T10:52:32.820Z
2018-09-13T22:02:18.773Z
2018-09-13T22:02:18.773Z
Artelius
<h3>Simply put, we do not <em>count</em> from zero, we <em>shift</em> from zero</h3>

<p>You can think C as a neat way to <em>not</em> write different assembly for every architecture/machine/processor in existence. Instead, take a <a href="https://www.bell-labs.com/usr/dmr/www/cman.pdf" rel="nofollow noreferrer">simple and short</a> macro-like language for a abstracted machine, compile that, and <a href="http://man7.org/linux/man-pages/man2/brk.2.html" rel="nofollow noreferrer">brk()</a> your way on abstracted memory.</p>

<p>But abstracted memory is only a sequence of bytes, you need a way to refer to specific segments. Enter pointers. But to not make every item a allocation (think of a string where every char is separately allocated) the next step is "lists". The most compact list<sup>1</sup> is a pointer to the first element, and then put every other element in adjacent slots.</p>

<p>Every element is, then, indexed as <em>shift from first</em>. And because that, the shift <em>index</em> starts from zero.</p>

<hr>

<p><sup>1</sup> This is from a era when you need entire reunions to decide if is worth spend whooping <strong>52 bytes</strong> to have <a href="https://pt.wikipedia.org/wiki/The_Mythical_Man-Month" rel="nofollow noreferrer">your system</a> know about leap years...</p>

CC BY-SA 4.0
2018-09-03T13:55:59.200Z
2018-09-09T15:38:39.347Z
2018-09-09T15:38:39.347Z
André LFS Bacci
<p>Why not?</p>

<p>Why not count from zero?  (This answer is a bit like <A HREF="https://cseducators.stackexchange.com/a/5031/1676">Buffy's answer</A>, but a bit simpler logic than many of the other answers.)  Zero is a perfectly valid number.  So why not use it?  Failing to use that available number is just a waste of the possibility of using that number.  You wouldn't want to start lower, since negative numbers may be a bit more complicated to need to consider, and may even be unavailable (when using unsigned numbers).  But zero is available, so why waste the possibility of being able to use that number?</p>

<p>If you do that, it's like the 63 SPT (sectors per track/head) limit that contributed to the <A HREF="http://www.pcguide.com/ref/hdd/bios/sizeMB504-c.html" rel="nofollow noreferrer">504 MiB / 528 MB) Barrier</A>.  That used a 1-based count.  If a zero-based count were used, a limit would have been 512 MB instead of 504 MB.  In a day and age when hard drives were counted in megabytes, that limit was nearly 1.6% smaller because someone decided to do a one-based count for one of the numbers.  So, keeping that real-world actual cost in mind, what benefit is there to trying to exclude zero?  If there isn't one, then don't do it.</p>

<p>Standardizing on one number is nice.  When I was ten years old, I knew how to program.  Sometimes I counted from one (e.g., "<code>for(x=1;x&lt;=10;x++)</code>" ), while other times I counted from zero (e.g., "<code>for(x=0;x&lt;10;x++)</code>" ).  Sometimes I would mix up those methods, and create a fencepost bug (using "<code>for(x=0;x&lt;=10;x++)</code>" ).  Later in life, I was pretty strongly compelled to count from zero and drop the test for equality (just testing for inequality using <code>&lt;</code>, instead of "less-than-or-equal" using <code>&lt;=</code>), and once I got into a standardized habit, I found myself to be far less likely to be making those off-by-one errors.</p>

<p>Ultimately, the code of in many "high level" programming languages is just meant to be converted into "low level" assembly language, which is designed to operate the same way as an actual chip.  Zero is kind of a special number (having unique properties with addition and multiplication), while one has less special behavior (having a similar unique property with multiplication, but not addition).  So it makes a bit of sense for zero to be special.</p>

<p>Also, if you think of the "what's left", zero is more logical.  If you count down ("'for x=10;x;x--)`"), then do you want to exit when there is one job left, or zero jobs left?  Zero is more sensible in that particular case, and that may be a key reason why some of the Intel Assembly Language operators perform the way they do.</p>

CC BY-SA 4.0
2018-09-07T04:07:41.310Z
2018-09-07T04:07:41.310Z
TOOGAM
<p>I think that one of the first programming languages to use zero-based indexing was BCPL. In BCPL, pointers and integers are interchangable, and arrays are represented by pointers. Subscripting uses the operator <code>!</code>, so you can get the first and second members of an array using <code>A!0</code> or <code>A!1</code>. These are defined to be equivalent to <code>!(A+0)</code> and <code>!(A+1)</code> where the unary <code>!</code> operator dereferences a pointer. It's neat, simple, and consistent, and it wouldn't work with 1-based addressing.</p>

<p>A lot of BCPL ideas were carried into C, and the rest is history.</p>

<p>But although zero-based indexing seems to work best for system programming languages, there are many modern languages that chose to start at 1. XPath is an obvious example. I think the rationale there was that it was expected to be used by non-programmers (e.g document authors) and you can't expect a document author to think of the first chapter in a book as chapter 0.</p>

CC BY-SA 4.0
2018-09-06T12:37:15.973Z
Indeed BCPL seems to be origin of 0-based indexing. We can try to explain to ourselves or to pupils why indexing starts from 0, but the fact is that it only does so in certain languages, and that most of those do so out of historical reasons. This blog shines some light on the origin of 0-indexing: http://exple.tive.org/blarg/2013/10/22/citation-needed/
idrougge
CC BY-SA 4.0
2018-09-06T13:31:22.613Z
Nice blog article. I'm amused by the notion that we're more likely to have heard of Eben Upton than of Martin Richards.
Michael Kay
CC BY-SA 4.0
2018-09-06T13:38:34.943Z
... It reflects that the author is clearly digging into software history for the first time and is suprised by his discoveries, thinking that perhaps no-one else knows this. However, his conclusions are a bit inconsistent. Zero based indexing in BCPL was an inevitable consequence of having pointers rather than arrays as the fundamental data structuring concept, it wasn't to make array indexing more efficient.
Michael Kay
CC BY-SA 4.0
2018-09-06T13:42:50.047Z
Since we're on Computer Science Educators, I might mention that Martin Richards and Steve Bourne between them probably taught me everything I really needed to know about programming -- mainly by example; they both wrote beautiful code.
Michael Kay
CC BY-SA 4.0
2018-09-03T10:20:44.267Z
2018-09-03T10:20:44.267Z
Michael Kay
<p>Counting is always 100% arbitrary. <strong>Counting from 0, from 1 and from 7 - all make exactly same sense.</strong> Our reliance on indexing from 1 in real life is no different than our reliance on 10 as base of positional system. It's nothing but a convention.</p>

<p>The only issue is "How do I remember where do we agreed to start counting at?". From there comes the lead-on question: "What is the default value for integer variable?" or "If you started with a freshly initialized integer, what would you think would be it's value?"</p>

<p>And this is the reason why we start at 0: <strong>Integers start at 0, so it's helpful to map the first entry of an array to the first value of a variable capable of indexing it.</strong></p>

CC BY-SA 4.0
2018-09-13T10:45:28.927Z
BCPL, where zero-based indexing probably originated, didn't initialize variables. So that's hardly the right justification. Also, *integers don't start at 0*. Integers don't *have* a start. As for a default in your favorite language (if it even has one), that's entirely arbitrary - zero is convenient in pre-zeroed memory, but before modern memory management, there were no definite default values. A pretty common practice is to always initialize variables with a meaningful value, rather than some "whateverdefault" - e.g. if you want a control variable that counts down, initialize it with count.
Luaan
CC BY-SA 4.0
2018-09-18T08:12:04.847Z
@Luaan Yeah, this is what I meant by saying that it's arbitrary. I don't agree with BCPL as the origin. In asm when you think of a memory area as an array, you index it with addr+(0*stride), addr+(1*stride), etc
Agent_L
CC BY-SA 4.0
2018-09-18T11:10:01.487Z
In assembly, you didn't have any abstraction (at first). Indexing an array is already an abstraction - it's a map between "I want the 3rd element of the array" and what's actually needed to get that particular element. The fact that you don't need to know the element size in BCPL (or anything else about the array) is a big difference. Indeed, in assembly, you'd often see very complicated addressing patterns that were tailored to the capabilities of the hardware, rather than the logical structure of the program; in C, if you wanted the next element, you did `element++`.
Luaan
CC BY-SA 4.0
2018-09-18T11:13:18.803Z
Now, it's true that in C, that actually was a low-level pointer operation. But that's not the purpose of it, that's just a constraint to make the compiler simpler. The meaning is still "the next element" or "the 3rd element", not "pointer + 0x12". C is a rather bare language, but it's still way above the abstraction of then-assembly. Meanings started to creep into things that used to be pure procedural code. Of course, it couldn't compare to anything like LISP - the ties to hardware were far too strong for that. But there were things like `0` as pointer value, or what `i++` means.
Luaan
CC BY-SA 4.0
2018-09-18T12:12:31.107Z
@Luaan This is why I wrote "when you **think** of a memory as an array". It doesn't matter if the abstraction is a part of a language or your train of thought. BCPL built up on established standards of thinking about a program. I don't really get where are we going, because I feel like you're restating my concepts but phrase them like counter-arguments. If you believe that my answer can be improved, then it appears you need to be more specific.
Agent_L
CC BY-SA 4.0
2018-09-10T13:53:58.353Z
2018-09-10T13:53:58.353Z
Agent_L
<p>An example from a non-technical field where counting is universally from 1 and it has strange consequences.</p>
<p>In music, chord intervals start from unision or 1st — that is the two notes sound the same note — and go up 2nd 3rd 4th 5th 6th 7th 8th which is an octave. Thus:</p>
<p><a href="https://i.sstatic.net/Aqnit.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Aqnit.jpg" alt="Octave intervals" /></a></p>
<p>Now we go further up from the octave :
9th 10th 11th 12th 13th 14th 15th = 2 octaves</p>
<p>Notice something strange? The 8th of the octave did not double to a 16th of two octaves!</p>
<p>What gives?
The real issue is this:</p>
<h1>An octave has 7 notes!</h1>
<p>&quot;Octave&quot; itself is a misnomer!</p>
<p>ie C, D, E, F, G, A, B is the &quot;octave&quot;</p>
<p>After that the &quot;loop&quot; repeats at/from the next C.</p>
<p>And so if we had counted — better measured — the C-C chord — the so-called &quot;unision&quot; — as a zeroth then C-D, a single whole-tone step, would be a first and so on upto C-C being a 7th. And continuing C-(next)C would be a 14th thereby keeping our (arithmetic) expectation intact.</p>
<p>Of course the key as many others have pointed out is that the distance <em>measured</em> rather than <em>counted</em> between C and itself <strong>is zero!</strong></p>
<h1>In more Math language</h1>
<p>In ℤ {0,1} are special</p>
<blockquote>
<p>The infinite cyclic group (ℤ,+)
has 0 identity and 1 generator</p>
</blockquote>
<blockquote>
<p>The field ℝ (or ℚ) has no generator
ie 0 remains special, 1 less so.</p>
</blockquote>

CC BY-SA 4.0
2020-10-05T10:42:31.600Z
It gets even weirder when you consider that a second plus a second plus a second is a third, and that you can add unison's (the first) infinitely without ever moving at all.
Ben I.
CC BY-SA 4.0
2020-10-05T11:06:31.543Z
Umm.... Cute observation @BenI. But this is a composition of two different things: the minor one being counting from 1 the major one being the wondrous irregularity of the scale. Which itself we experience through two *big* simplifying approximations: the uncountable infinity of frequencies reduced to (western) music (C# spelt different from Db but the C-D whole tone = D-E whole tone). Then reduced once again to 12 notes of the keyboard
Rushi
CC BY-SA 4.0
2020-10-05T14:46:27.147Z
Cute observation is what I was going for :)  But it's truly exactly the same observation as octave plus octave is fifteenth, just with smaller numbers.
Ben I.
CC BY-SA 4.0
2020-10-05T14:59:29.857Z
There's also a bit of something not quite right, actually. The octave doesn't have 7 notes; the octave is an interval (so at most, it only has 2 notes), and it is named for being the eighth note along the scale up from the tonic. So I think you meant to say "an octave of a major scale only has 7 notes", but even this wouldn't quite be correct.  It would be correct to say that "an octave of a major scale is comprised of seven notes beyond its initial note".
Ben I.
CC BY-SA 4.0
2020-10-05T15:55:45.497Z
@beni. «but even this wouldn't quite be correct. It would be correct to say that "an octave of a major scale is comprised of seven notes beyond its initial note"» Well there's a programming theorem that every top tested while can be written as a bottom tested do-while. And conversely. I wrote the 7 as CDEFGAB. you could write (reference C) DEFGABC. Which ever way you count there are 7 distinct followed (or preceded) by the "loop"
Rushi
CC BY-SA 4.0
2020-10-06T03:14:42.593Z
But neither of those is an octave, those notes outline major and minor sevenths, respectively. The octave only has two notes, such as CC.
Ben I.
CC BY-SA 4.0
2020-10-06T03:43:05.473Z
Let me try a different tack @BenI. {a, b, c, d, e, f, g} is a set with 7 elements (cardinality 7). You're not allowed 'h' (unless you're German!). In the music world (assuming a fixed scale/mode, no accidentals, modulation and other fancy stuff) **your palette consists of 7 "colours"**
Rushi
CC BY-SA 4.0
2020-10-06T10:15:47.130Z
Perfect. I agree! This is all correct.
Ben I.
CC BY-SA 4.0
2020-10-05T06:55:10.587Z
2020-10-05T07:46:28.980Z
2020-10-05T07:46:28.980Z
Rushi
<p>I think it's best to view addresses and indices not as identifying objects or elements, but rather the spaces between or on either side of them.  Thus, an array with four elements would have the following indices:</p>

<pre><code>Addr:   Base+0  Base+1   Base+2  Base+3  Base+4
.         V       V        V       V        V
Indices:  0       1        2       3        4
Elements   [FIRST] [SECOND] [THIRD] [FOURTH]
</code></pre>

<p>Each element is associated with two addresses--the one immediately preceding it and the one immediately following it.  The address immediately following any element other than the last will immediately precede another element, and likewise the address immediately preceding any element other than the first will follow another element.  Even though each address other than the first and last will be associated with two elements (one preceding and one following), by convention applying the <code>*</code> operator to an address yields the one following.</p>

<p>Note that unlike the "half-open interval" view, this approach does not require any special handling for pointers that go one beyond the last element.  The address "Base+4" above is associated with the four-element array just like any other, but the <code>*</code> operator cannot be applied to it because that operator would require the ability to compute the next address.</p>

CC BY-SA 4.0
2018-09-05T01:54:04.577Z
I like this.  This is also a useful way of thinking about labels in assembly language (as zero-width).  Addresses and labels don't have any natural width associated with them; that depends on what type of load/store you do.  (The type system in most languages associates an element width with a pointer, but this is why you can't add/subtract `void*` in C.)
Peter Cordes
CC BY-SA 4.0
2018-09-04T19:31:14.620Z
2018-09-04T19:31:14.620Z
supercat
<p>Human counting intuitively revolves around two <strong>different</strong> cases:</p>
<ol>
<li><p>The total element count in a list or a collection:</p>
<p>We do so by assigning '1' to the first element and counting upwards (Rarely, we may choose to assign '0' to the first element, as in the floor counting system in the UK where the first floor is called 'Ground floor'). Example: Counting the total apples in a bag by starting the count from 1.</p>
</li>
<li><p>The total distance traveled from the first position:</p>
<p>We do so by assigning a certain value to the starting position, and then adding the offset on it as we traverse a certain distance. Now, what value to assign to the starting position to simplify the calculation? As you might have probably guessed, assigning 0 to the starting position makes calculation much easier. Example: Measuring the distance means keeping the measuring tape such that the &quot;zero&quot; reading is at the starting position. This is what others have pointed out as well.</p>
</li>
</ol>
<p>Let's get to the world of computers. When we talk about the first element of an array being called '0', we are not talking about the element count, but rather the position in the array, just like in the <strong>second case above</strong>. It's essential to recognize this distinction, as our intuition might lead us to compare computer numbering with the first case in human counting. So assigning '0' to the first value of the array simplifies indexing. This means in a computer's memory, the address of the next element can be determined using the offset rule.</p>
<p>While compiler optimizations might have likely been implemented to accommodate this convention, the influence of languages like C, which starts indexing from '0' (unlike FORTRAN that starts from '1'), has solidified this approach. Just like there is no need to alter a measuring tape where the reading starts with 1 instead of 0, even though human brain is already &quot;optimized&quot; (smart) to calculate the distance even if the reading started from 1.</p>

CC BY-SA 4.0
2024-01-25T11:33:15.673Z
2024-01-25T13:02:22.993Z
2024-01-25T13:02:22.993Z
Sunlightwings
<p>In computer science, we usually count starting from 0.  Is there any effective way to explain why, to new programmers who ask why?</p>

<p>I've read a bunch of different sources that list several reasons for 0-indexing.  However, they either seem unconvincing, or seem hard to explain to a new programmer who doesn't have much experience with computer science yet:</p>

<ul>
<li><p>Zero-based indexing lets you write loop conditions as <code>i &lt; n</code>; with one-based indexing, we'd have to write <code>i &lt; n+1</code>, which saves one instruction.  This makes no sense to me; <code>i &lt;= n</code> seems like it would be fine.</p></li>
<li><p>In C, we can use <code>*a</code> to access the first element of array <code>a</code>.  This doesn't seem very relevant today for a new student who isn't programming in C.</p></li>
<li><p>With zero-based indexing, the expression <code>a[i]</code> compiles to an operation on memory address <code>a + c*i</code> where <code>c</code> is a constant representing the size of a single array element; with one-based indexing, it would need to compile to <code>a + c*i - c</code>.  This reason seems debatable today (couldn't a modern compiler often optimize this away?), but more importantly, I don't really want to be explaining memory addresses to a new programmer who doesn't understand memory layout and maybe doesn't even understand arrays yet.</p></li>
</ul>

<p>Is there a better way to explain why to a new student who is just getting started with computer science?</p>

CC BY-SA 4.0
2018-09-03T02:05:53.543Z
As an extra source of input, have you seen the other question [Real life examples of 0-indexing](https://cseducators.stackexchange.com/q/213/104)? Might be some help there.
Gypsy Spellweaver
CC BY-SA 4.0
2018-09-06T01:19:42.890Z
Please avoid adding your answers in the comments. It gets around our quality control systems, for example downvoting and collaborative editing. It also unfairly puts your answer above everyone elses. I've moved these answers-in-comments [to chat](https://chat.stackexchange.com/rooms/82811/discussion-on-question-by-d-w-why-do-we-count-starting-from-zero) for posterity. Please avoid adding future answers in the comment section.
thesecretmaster
CC BY-SA 4.0
2018-09-09T00:45:09.873Z
**Please do not use the comment section to answer the question.** I will be periodically deleting all answers-in-comments. Instead, you're welcome to write up your thoughts as an answer, using the form at the bottom of the page.
thesecretmaster
CC BY-SA 4.0
2022-05-18T21:15:57.700Z
It is actually simple to answer: we start counting from zero instead of one for the same reason that rulers and measuring tapes start from zero instead of one. The "counting" index is the offset from the array's beginning, so it makes sense that the beginning is offset from itself by zero, or in other words, it is where it is.
NOT CSEducator
<arrays>
Why do we count starting from zero?
# Why do we count starting from zero?

(Asked by: username_0 on 2018-09-03)

In computer science, we usually count starting from 0. Is there any effective way to explain why, to new programmers who ask why?

I've read a bunch of different sources that list several reasons for 0-indexing. However, they either seem unconvincing, or seem hard to explain to a new programmer who doesn't have much experience with computer science yet:

* Zero-based indexing lets you write loop conditions as `i < n`; with one-based indexing, we'd have to write `i < n+1`, which saves one instruction. This makes no sense to me; `i <= n` seems like it would be fine.
* In C, we can use `*a` to access the first element of array `a`. This doesn't seem very relevant today for a new student who isn't programming in C.
* With zero-based indexing, the expression `a[i]` compiles to an operation on memory address `a + c*i` where `c` is a constant representing the size of a single array element; with one-based indexing, it would need to compile to `a + c*i - c`. This reason seems debatable today (couldn't a modern compiler often optimize this away?), but more importantly, I don't really want to be explaining memory addresses to a new programmer who doesn't understand memory layout and maybe doesn't even understand arrays yet.

Is there a better way to explain why to a new student who is just getting started with computer science?

**Tags:** arrays

> **Comments:**
> **username_1**: As an extra source of input, have you seen the other question [Real life examples of 0-indexing](https://cseducators.stackexchange.com/q/213/104)? Might be some help there.  
> **username_2**: Please avoid adding your answers in the comments. It gets around our quality control systems, for example downvoting and collaborative editing. It also unfairly puts your answer above everyone elses. I've moved these answers-in-comments [to chat](https://chat.stackexchange.com/rooms/82811/discussion-on-question-by-d-w-why-do-we-count-starting-from-zero) for posterity. Please avoid adding future answers in the comment section.  
> **username_2**: **Please do not use the comment section to answer the question.** I will be periodically deleting all answers-in-comments. Instead, you're welcome to write up your thoughts as an answer, using the form at the bottom of the page.  
> **username_3**: It is actually simple to answer: we start counting from zero instead of one for the same reason that rulers and measuring tapes start from zero instead of one. The "counting" index is the offset from the array's beginning, so it makes sense that the beginning is offset from itself by zero, or in other words, it is where it is.  

---

## 31 answers

### Answer by username_22 on 2018-09-03. Score: 229

None of the reasons you suggest really get to the heart of why we use zero-indexing in CS. Dijkstra's [EWD831](https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html) explains why this convention works out the best. It comes down to the fact that we want to represent sequences of integers as half-open intervals that are inclusive on the start side.

> To denote the subsequence of natural numbers 2, 3, ..., 12 without the pernicious three dots, four conventions are open to us  
> a) 2 ≤ i < 13  
> b) 1 < i ≤ 12  
> c) 2 ≤ i ≤ 12  
> d) 1 < i < 13

To paraphrase Dijkstra:

* (a) and (b) have the advantage that subtracting the bounds gives you the length, which is convenient because you don't need to remember to add or subtract 1.
* (a) and (c) have the advantage that sequences starting with zero don't need a negative lower bound -- and negatives are no longer natural numbers.
* (a) and (d) have the advantage that if you create an interval that starts with zero and shrink it down to zero-length, you don't need a negative for the upper bound.

Because of the above, we want to write all of our intervals as (a).

Once you accept that (a) is the correct way of specifying intervals, indexing an array of length N as [0, N) is much nicer than [1, N+1).

---

Two additional notes in favor of using (a) for intervals.

The first point above is important because half-open intervals nicely decompose into other half-open intervals. This makes implementing divide-and-conquer algorithms like merge sort significantly less error prone.

For example:

* [4, 14) can be broken into the equal-sized intervals [4, 9) and [9, 14), and the middle index is computed as $9 = \frac{4 + 14}{2}$. This is quite clean and nice.
* [4, 13], decomposes into [4, 8] and [9, 13], where you get the end of one sequence as $8 = \frac{4 + 13 + 1}{2} - 1$, and the beginning of the next sequence as $9 = \frac{4 + 13 + 1}{2}$. It's easy to forget to add or subtract 1 somewhere.

It's also a bit jarring to specify intervals with (b), because it feels unnatural to skip the first element when you're writing a loop.

---

As for how to explain the above to your students, I think that they just need to accept that breaking sequences of integers in half is something they'll do later on, and then a few examples will quickly point to [,) intervals and zero indexing as the most natural choice.

> **Comments:**
> **username_1**: The half-intervals decomposing into half-intervals is a nice touch. Dijkstra's explanation does good job of justifying the use of the common scheme within CS as it was becoming a modern science.  
> **username_17**: Nice contribution and good insight. You've made this corner of the internet a better place :) Welcome to [cseducators.se]. Take a look around, I'd love to know what else you can add.  
> **username_23**: While a good reason to start indexing at 0, it feels much easier and more natural to mentally parse (d) and especially (c) than (a) or (b) - "numbers from x to y" in natural language usually means inclusive of both (or exclusive of both)  
> **username_24**: Note that adopting the convention more widely helps in a number of other scenarios, not just array indices.  For instance, it [eliminates a whole class of errors in date handling](https://sqlblog.org/2011/10/19/what-do-between-and-the-devil-have-in-common).  If you're doing something like a fee scale for package weights, the exclusive upper-bound also username_12ws measurement result to be independent of the limit specified (ie - if an inclusive upper bound is given as `2.9` but the scale measures as `2.95` you have issues).  
> **username_25**: @username_23: Fully closed or fully open may be "more natural," but the subtraction property of half-open is extremely important.  The interval [a, a+b) is exactly b elements long, without any pesky +1 or -1 terms.  You simply cannot avoid having +1s and -1s everywhere when you use fully closed or fully open intervals.  
> **username_26**: This also matches the behavior of the modulo operator, the return value of which lies in [0, n). `number_of_values_ending_in_a_particular_digit[x % 10] += 1`  
> **username_27**: This is a good reason, but I think a more fundamental one is simply hardware: binary registers and memory locations representing unsigned integers have a 0 "all bits off" state. Indexing by one would waste that.  
> **username_28**: Every answer with Dijkstra in it is nice. But......... this answer seems to answer a completely different question, doesn't it? This answer only concerns itself with the openness of intervalls. Neither the quote from Dijkstra nor the rest of the answer has anything to do at all with the actual question - which is, to rephrase a bit, "why do array indices start at 0" (sic).  
> **username_29**: Those reasons don't seem entirely compelling in the argument of 0 vs 1.  For example, in the second point you can argue that sequences starting with 1 don't need negative numbers either, and in the third point, you can argue that sequences starting with 1 also don't use negative numbers for zero-length (although the counter-counter-argument is that they still require reversed bounds, which may be confusing).  And if you know that the lower bound is 1 then the upper bound in form (c) is also the length, no arithmetic required.  
> **username_30**: Good point about the half-open ranges. The other common  case where these come in useful is string manipulation. Having zero-based half-open ranges there makes substring positions and lengths a lot cleaner to work with.  
> **username_31**: What do you mean by "indexing an array of length N as [0, N)"?  
> **username_32**: "indexing an array of length N as [0, N)" - perhaps I'm not understanding the notation (especially the varied brackets), but surely an array with 0 ... N elements is not of length N?  

---

### Answer by username_1 on 2018-09-03. Score: 116

If I can modify the question, I can answer what I believe you are looking for.

---

The question is "Why do we count starting from zero?" The answer is "we don't" Not even in computer science do we "count" from zero. A list with 15 items in it from outside CS still has 15 items in it inside CS realms. Many languages include a `count` type function for arrays, and such a function would still return 15 for that list.

---

If the question becomes "Why do we *index* from zero?" then it has a different answer. This time the answer is "because that's the way everyone else does it." When we separate the concepts of "indexing" and "counting" things become simpler to explain. Often true of any concept, use the proper terminology and many difficulties are eliminated.

---

As to why we, as humans, index from zero, while counting from one, only requires a little thought before clarity arrives. Assuming a classroom environment, where the class period lasts for a specified time, perhaps 50 minutes, you can ask at very near, but after, a 60 second mark, how many minutes the class has been in session. If asked at 5:02 minutes into class, the answer will be five minutes. Ask them how long class had been in session five minutes ago, which would be around 0:20 into the class period. The answer should be zero minutes. Once they accept that it was zero minutes, even at 0:59 into the class, you can emphasize that even though the class time had not reached a full minute, it *is* still class time, and should have some way of "indexing" it. Since the number before one is zero, it must have an index of zero. Hence the "first minute" (by counting) has an index of zero.

The same thought experiments can be conducted with a ruler/tape measure, where the measure starts at zero, and the first centimeter/inch is called, and written, zero. The same concept applies to any distance, such as miles or kilometers, but those are harder to fit into the classroom. In the USA, most highways have "mile markers" that help in locating people for emergency responders. They mark the distance from the beginning of that highway on its south-western end. (The beginning is at the state line if it crosses from one state to another.) "Mile marker" 1 is set after the first mile is completed. "Mile marker" 0 is sometimes seen on the state line, though it is not always there. The first mile, in counting, has an index of 0.

As another example, though not quite as helpful, and requiring that the students have a level of algebra experience to apprehend it, is exponents. Limiting it to non-negative powers of ten and applying it to whole numbers only, we can use the fact that $10^0 = 1$ while $10^1 = 10$. The exponent represents the index for how many places to the right to move (again distance *to move*) the decimal point, while the *count* of the digits before the decimal point will be 1 larger.

Final demonstration: "What is the *index* of the first position on the volume knob below?" "What is the *index* of the last position on that volume knob?" "How many positions can you *count* on that volume knob?"

![Volume Knob](https://i.sstatic.net/dzHYQ.jpg)

---

Once the "index" vs "count" is solved, you can move into the CS realm, where the same practices are followed.

An array is "indexed" from zero and "counted" from one. Why? Because that is the way humans index and count. It certainly comes in handy when doing arithmetic with memory addresses, and there's nothing wrong with taking advantage of things that "just work" naturally. Similar shortcuts include dividing and multiplying by powers of two by shifting bits to the right of left. Its usefulness to the compiler, or the developer, however, is not the *why*. Such "benefits" are only side effects of "what was" before CS was a reality.

Bottom line is that index from zero and count from one existed a *very long* time before electronic computers were invented. Like any other science, computer science has to build upon what already exists before inventing new things. Zero-based indexing is one such "pre-existing" thing.

> **Comments:**
> **username_17**: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/83029/discussion-on-answer-by-gypsy-spellweaver-why-do-we-count-starting-from-zero).  
> **username_33**: "*If asked at **5:02** minutes into class, the answer will be five minutes. Ask them how long class had been in session five minutes ago, which would be around **0:20** into the class period.*" Can't tell if you're assuming it takes 18 seconds, give or take, to answer the first & ask the second question or if it's a typo. ;^)  
> **username_1**: @username_33 18 seconds is an estimate of the dialog time.  
> **username_32**: You are correlating continuous time with discrete "buckets" for storing things - completely irrelevant. To counter, I could say "in which minute are we when we are 0:20 into the class?" and the answer would be "the 1st". So why not index from 1? As for your volume knob, I would assume zero to mean zero volume - that would be an empty array; an array with zero elements. That does not mean the 1st element should be called element zero. Completely irrelevant and I can't believe this got 100+ votes.  
> **username_1**: @username_32 "How old is the child?" and "Which year is the child in?" also differ by one. It depends on teh question asked. "How many elements in the array?" and "What's the last index of the array?" differ by one. Interestingly enough, if you've used elementary school graphing, zero is also the beginning of each axis, known as the "origin." That difference between "count" and "index" is included in the opening of the answer. Of course, if you find this answer to not be helpful, for any reason, or none at all, you can still down-vote it.  
> **username_32**: @GypsySpellweaver - again - continuous time and continuous axes - irrelevant. The correct answer is username_20's. See also my "TLDR" comment there. Let's not clog up these comments further by going back and forth.  
> **username_34**: Great answer. You could have mentioned the concepts of "ordinal" vs "cardinal" for "index" & "count". Together with the answer that quotes Dijkstra, this is pretty much it.  

---

### Answer by username_20 on 2018-09-03. Score: 63

I'm surprised that the following hasn't been stated yet. All of the answers given so far seem to be "after the fact" explanations of something that is really based on the way people built most (not all) early computers as binary machines.

To make things a bit more compact here, I'll assume we are creating a 4 bit (nibble) based machine. We don't want to use more binary components to build a nibble than we need to because we are cheap, so we use four bi-stable components (relays, vacuum tubes, transistors). We think of (perhaps) the two states as zero and one rather than, say, red and green.

So we have (0000) through (1111) as the combinations of the four transistors of a nibble. We can interpret them any way that we like. Suppose we want to interpret them as integers. How shall we assign the different codes to integers. We *could* let (0000) represent 42, a fundamental universal constant, and (0001) represent 3, an approximation to pi and so on, but we realize pretty soon that any computations we want to do with such an encoding would be pretty complex - and complexity in a machine costs money. We are cheap, remember.

So we notice that the codings are actually binary numbers. Well almost nobody used binary numbers before this so we start to think about it seriously now, as they have an application. I note that some early computers were actually decimal, not binary, but they recognized that while convenient it wasn't cheap.

Now, using binary numbers, not just binary encoding, it becomes "obvious" that the codes represent zero through fifteen, not one through sixteen. Using (0000) to represent 1 just seems dumb at this level - and at this time.

Now, (bit later) we want to index an "array" of nibbles. How shall we do it. Well we assign index numbers to the individual cells. Suppose we have four such cells. How shall we do it? We *could* use (0001) through (0100) to index them (1 through 4), but now (a-ha) if we have **sixteen** nibbles to index but start with one we can only get (our count) to fifteen without using another nibble or letting (0000) represent the last (sixteenth) cell. That seems dumb, so we (a-ha) index from zero. Now we can index sixteen cells with sixteen codes and it is cheap and *pretty natural*. The only cost is a bit of confusion in the minds of beginning programmers, but others will pay those costs and our machines can be cheap.

No contest. Index from zero.

The other answers here explore why the arithmetic inside the machine is cheap this way, so I won't repeat it here. But note that all of this happened before any languages at all were invented other than the simplest of machine coding without any abstraction facilities at all. It was just economics and engineering. Make it simple, keep it cheap.

> **Comments:**
> **username_35**: Give your students this simple task and they will find the answer themselves: **Number these ten students, each with a unique number, but you can only use a single digit** - they will quickly come up with the solution to number then 0 to 9 - and that is why we index starting at zero, we don't like waste :-)  
> **username_36**: Interestingly, all the *early* languages have *one*-based (or *user-defined*) indexing (e.g. Fortran (1957), Algol (1958)), or don't have a notion of "array" at all (Lisp (1957)). Zero-based indexing is a rather *modern* invention.  
> **username_37**: Interesting that on rotary telephones 0 (with ten pulses) comes after 9, but then pulsing the line zero times doesn't really work physically.  
> **username_38**: @JörgWMittag: Interesting!  I wonder if designers of early languages were thinking that anyone who knew how computers and binary numbers really worked would just write in assembly language.  Early computers were slow, and early compilers presumably didn't optimize well / at all.  Anyway, this answer is exactly what occurred to me, too: letting an N-bit index address a full 2^N elements.  Power-of-2 buffer/object sizes are a big deal.  
> **username_20**: @PeterCordes, languages have been a search for higher levels of abstraction and the ability to write more complex programs without getting lost in the details of assembler. The assumption was that problems were outgrowing our ability to think about them in low level terms. Languages aren't a placebo for babies, but a tool for experts. For a shock, look at the Google home page. Then use your browser to look at the actual source for that. Now try to duplicate it in assembler. Note that even assembler is a language with _minimal_ abstraction, unlike machine code with none at all.  
> **username_38**: @username_20: Yes, I understand that's the other motivation for higher-level languages, and why I use `bash` as a shell instead of an interactive assembler where I'd type `mov eax, __NR_fork` / `syscall`.  But I thought 1958 was still early enough in the history of computing that performance might still trump everything for many problems.  I could easily be wrong.   Having grown up with C (and assembly), 1-based indexing seems totally unnecessary and unnatural *to me*.  I'm not familiar enough with the history of computing and the motivations of early language architects to rule out my guess.  
> **username_11**: @ScottRowe zero had 11 pulses, and one had 2 pulses. This was to stop the equipment reacting to random single pulses.  
> **username_6**: @PeterCordes It's one of the reasons so many computer scientists/engineers hated C and Unix - they took the "performance is better than correctness" approach, which was contrary to the prevailing thought "as computer software gets more complex, it's even *more* important to keep things correct". A correct program that's easy to understand gives you more opportunities for performance improvements too - most of the time when a C program was faster it did so by sacrificing correctness (e.g. ignoring boundary conditions). Dijkstra's lessons on sustainability and quality of software are great intro  
> **username_38**: @username_6: I'm not familiar with early C or Unix being unpopular for that reason. Early compilers sucked at optimization, so to make things fast people left out safety checks?  These days optimizing compilers can hoist bounds-checks out of loops if it's the same bounds on every iteration, so you can write safer code (especially with C++ to hide the noise behind `std::vector`).  C makes correctness optional, and makes you do it yourself, but it's still possible to write correct C functions / programs.  These days it's a nice language for writing hot loops, but not great for maintainability.  
> **username_38**: @username_6: Anyway, I don't see what zero-indexing has to do with correctness in any given language.  zero-indexing isn't *why* C makes unsafe code more easily possible.  Correlation / causation?  
> **username_6**: @PeterCordes You need to compare early C with languages of the time - C lacked pretty much all the things that other languages used to help you write correct programs. The goal in C was simplicity on the compiler and potentially performance, the trade-off was effort on part of the programmer. Contrast the difference between, say, iterating over an array in a for loop and doing a `map` - in the first case, you've opened yourself to potential incorrectness (out-of-bounds etc.), in the second these don't even make sense. C's design went directly against what those people thought was good design.  
> **username_20**: @username_6, don't lose track of the fact that C excelled at the task it was actually designed for. Kernighan and Ritchie were, at the time, at Bell Labs looking for a Better Assembler for a "spare" DEC PDP-7 computer they were using to develop Unix. It has the features it has precisely to match instructions in the PDP assembler set. That it was used for other purposes is a fact of history, of course, but for its designed usage it was near ideal. Ritchie wasn't trying to outdo Algol (or COBOL, of course), just do assembler more effectively.  
> **username_20**: @username_6, however, don't conclude from the above that I think C is a _good_ or even _adequate_ solution for modern programming. I would use it if I were writing device drivers and such, but prefer a safer language with  features such as those described by user username_38. Even safe auto-typing is a big win. Actually safe anything is a big win, especially memory management.  
> **username_39**: @username_11 - That's certainly not the case for British lines, and wikipedia suggests it wasn't the common system (https://en.wikipedia.org/wiki/Pulse_dialing).  We used to have fun by dialing people's numbers by hitting the hangup button the appropriate number of times.  Well, maybe "fun" is pushing it.  
> **username_11**: @Guyg I did it to defeat the lock (in England), and I had to add one to each number to get it to work.  
> **username_39**: @username_11 - I could swear I used to use 1 for 1, 2 for 2, etc, then 10 for zero (also in England).  Some quick Googling seems to confirm this, but I'm happy to be corrected...  
> **username_11**: @guyg I just tried it, it seems that you are correct. I wonder where I got that idea from.  
> **username_40**: @JörgWMittag yes but the thing that was established before arrays/indeces was that numbers themselves start at 0 in binary.  Because numbers start at 0 it is most natural for indexing to start at 0.  
> **username_41**: @JörgWMittag "*Zero-based indexing is a rather modern invention.*"  It's been around since the first assembler.  
> **username_42**: @username_11 IIRC the pulses are when you *lift* the button. There's 1 *pulse* for 1, but you have to press it down first.  
> **username_43**: @PeterCordes Early computers didn't have assemblers, programs were written in machine language directly.  
> **username_43**: This answer addresses the question as I understood it.  
> **username_38**: @username_43: Wasn't assembly well-established before higher-level languages came along?  Hmm, maybe not, but same difference in machine code directly: you add an offset to a pointer to get a new address.  (At least on machines that *have* normal address registers for indirect addressing, or memory-indirect addressing)  And/or you have indexed addressing modes.  I don't think any hardware ISAs had 1-based indexed addressing, but I don't actually know really early ISAs.  (I know 8-bit ISAs like 8080 have pointer registers, though.)  
> **username_43**: @PeterCordes Direct machine code programming preceded assembly languages, assembly languages were the first higher level languages. Machine code vs assembly code: https://stackoverflow.com/questions/466790/assembly-code-vs-machine-code-vs-object-code  
> **username_38**: @username_43: yes, I know that.  I have a gold badge in the `[assembly]` tag over on SO.  My point was that normal hardware has 0-based indexing / pointer-math, whether you generate machine-code from asm or write the machine code directly.  And my other point was to acknowledge that maybe I should have said "machine code" instead of "assembly" when talking about alternatives to higher-level languages like Fortran, if asm wasn't already widespread before higher-level languages were first being developed.  
> **username_32**: TLDR: 0 is the 1st binary number of relevance to electronics and computing and therefore when talking about sets of binary numbers, we use that valuable precious resource of the zero value in the limited binary number set available when computing was being invented. *This* is the most sensible answer. Because the code will need to *match* a binary 0000 when referencing the 1st element of a set. Kudos.  

---

### Answer by username_36 on 2018-09-03. Score: 40

You have already gotten several good answers about why zero-based indexing is useful, and you have been explained the difference between indexing and counting.
I now want to challenge the basic premise of your question: it is not, in fact, universally agreed-upon that indexing starts at zero.
In Excel, which is arguably the most widely-used programming language in the world (even though it doesn't look much like a "traditional" programming language), row-indexing starts at 1 and not 0, and column-indexing starts at A and not ε.
In Visual Basic, the programmer can choose between zero-based and one-based indexing as the default indexing on a per-module (per-file) basis with the Option Base declaration. Plus, the programmer can declare the exact index range for each individual array using the To keyword in the array declaration, e.g.:
Dim Count(100 to 500) as Integer

This declares an array of integers named Count with indices ranging from 100 to 500 (inclusive).
In the "Wirthian languages", i.e. Pascal and all its successors (Modula-2, Oberon, Component Pascal), arrays can be indexed by any arbitrary range of scalars (except reals).
type
   foo = array[-10 .. 10] of real;
   (* an array of reals with indices ranging from -10 to +10 *)

   bar = array['b' .. 'g'] of 100..200;
   (* an array of integers from 100 to 200 with indices ranging from 'b' to 'g' *)

   weekday = (monday, tuesday, wednesday, thursday, friday, saturday, sunday);
   baz = array[tuesday..friday] of boolean;
   (* an array of booleans with indices ranging from tuesday to friday *)

The Wirthian languages, in turn, inherited this from ALGOL-60 and ALGOL-68.
Ada is similar, any discrete type can be used as the index type. Interestingly, idiomatic Ada style suggests using a range starting from 1 and not 0 when using an integer range as indices.
In Eiffel, which is heavily inspired by Wirthian languages, array indices have explicit lower and upper bounds which can be any signed 32-bit integer, so you could have an array with indices ranging from -1000000 to -1, for example.
In Fortran, the default is to start at 1, but like ALGOL, Pascal, Eiffel, and VB, you can specify any arbitrary lower and upper bound.
In Matlab, indexing starts at 1. In APL and Perl, you can choose.
Even in the "real world", there are different schemes. E.g., in Germany, the ground floor, i.e. the floor you enter from street level is called "ground floor", and is usually labelled 0 on elevator buttons that use numbers ("EG" if using letters). The floors above ground level are called "1st upper floor" (and so on) and labelled 1, 2, etc. (or "OG 1", …) The floors below ground level are called "1st lower floor" (and so on) and numbered -1, -2, etc. (or "UG 1", …)
In the US, "1st floor" is the floor at ground level.
Apparently, in Barcelona, there is a "ground floor", a "primary floor", and then the "first floor" is two stairs up from ground level.
There is an interesting discussion about this on the Wiki: http://wiki.c2.com/?ZeroAndOneBasedIndexes
I also found an essay that compares the syntactic and semantic noise of typical tasks using many different indexing schemes: http://enchantia.com/graphapp/doc/tech/arrays1.html

> **Comments:**
> **username_1**: It would seem that in Barcelona the "first floor" is one floor above the "primary floor", which name suggest that it is the "origin" for the building's life. The "ground floor" is presumably where garage, storage, utilities, and other facilities exist while regular rooms (kitchen etc.) are on the primary floor. Servants' quarters, are also likely to be "below" the primary floor. The ground floor would, presumably, have an index of -1.  
> **username_11**: In one university I have visited, the floor numbers were in feet above sea level. So not even consecutive. (This is also discussed here https://cseducators.stackexchange.com/a/215/204 )  
> **username_50**: The reason for the numbering of floors in Barcelona is due to an old building regulation which dictated no buildings could have more than six floors. To work around this restriction, extra floor names were added so that the maximum numbered floor was always #6. The extra floor names are "Entresuelo" and "Principal" just above the ground floor, and "Atico" and "Sobreatico" just above the sixth floor. (Not all buildings will have all of these floor names).  
> **username_51**: There's nothing factually incorrect about these examples but it doesn't mean that it's logical.  The first hour of the day on a 12 hour clock starts is 12 (while minutes start at 0) and the second hour starts a 1.  A 24 hour clock starts at 0.  Which makes more sense?  
> **username_52**: To add a floor counting example, in some parts in Germany counting starts with ground floor ("Erdgeschoss"), then floor 1, in other parts, counting starts with floor 1 at the ground.  (I almost installed a network in the wrong floor).  
> **username_52**: Next: In Siemens buildings, it is a tradition that the most lower floor gets number 1, so normally the buildings have (at least) one basement so ground level has number 2 in elevators (which is obviously confusing to most guests)- but if the building has more than one basement- it is not easy to know which number has the ground level- not very convenient for guests or imagine fire alarm.  
> **username_53**: *Nothing* Wirthian is inherited from ALGOL-68.  
> **username_46**: +1, but this is only half the answer. The other half is that in the 70's C made the choice to directly support only indexing arrays from 0, as this made the compiler simplest (which was really C's primary design goal). Because C compilers were so simple, they were easy to make and put on any machine, and as a result of this and a few other bits of historical luck, C became super popular. As a result of that, a whole host of other languages took their lead from C.  
> **username_36**: @username_52: The Wiki discussion I linked to has an even more confusing example. At IBM Rochester, they use the same numbering, but the buildings are so tightly interconnected that they look and feel like *one* building. So, you could walk a couple of meters on the ground floor and pass from floor 2 to floor 3 without even noticing, just because you happened to step from a building that has 1 basement to a building that has 2.  

---

### Answer by username_17 on 2018-09-03. Score: 23

When I've explained this to beginning students, I don't stray far from your third reason, though I agree that the beginning of arrays is early to introduce the concept of memory addresses. Among other things, that invites about your variable, `c`, when the only variable they need to worry about is `i`.

Instead of memory addresses, I talk about distances from the start. I've given a sample below using paper and a pencil as a reference point, though in my classroom I use the whiteboard and hold a marker. All of the numbers are in little boxes, and together they form a rectangle.

> Look at the list of numbers on the paper. We all know about ordinal numbers, "first", "second", "third", and so forth. But when we program, we actually refer to the list numbers a slightly different way, as 0, 1, and 2. This is called 0-based indexing, and the reasons for it don't matter right now. What matters is that the **first** item on the list is actually item **0**.
>
> Honestly, that's all you need to know to use arrays correctly. But if you want a hint about why we actually do this, you can think about zero-based indexing as the distance from the head of the array.
>
> So, if I'm at the head of the array, how many moves do I have to make to read the first number? No moves, I'm already there. What about the second number? I make one move to get there. The fourth number? One, two, three moves.
>
> Beyond the most important fact that we start counting from 0, thinking about it as "moves" is actually a good way to think about array indexes, because **when we come back to this topic later**, you'll see that the distance from the head turns out to be an important concept for understanding a lot of things a computer does. Don't worry we'll get there soon enough.
>
> So, for now, what is the index for this spot in the array? *(I point to a random index, wait for the students to arrive at the answer.)* Good, well done. Now, moving on to ...

> **Comments:**
> **username_54**: 'cardinal numbers, "first", "second", "third"'. These are ordinals, not cardinals. Cardinals count amount. Ordinals count order.  
> **username_17**: @username_54 Yes, they are. What an embarrassing error! Thanks for pointing it out, I'll fix it now.  
> **username_20**: Ah, but some of us are willing to say zero-th, also.  

---

### Answer by username_44 on 2018-09-03. Score: 10

> In computer science, we usually count starting from 0.

In **programming** or in **(theoretical) computer science**?

**In Programming**

In C programming language you count from 0 to (N-1). And of course in languages which are influenced by C: Java, JavaScript, PHP, C#, C++...

You already named the reason for this:

> In C, we can use `*a` to access the first element of array `a`.

... and because `a[i]` is the same as `*(a+i)` the first index of the array must have the index 0.

> This doesn't seem very relevant today for a new student who isn't programming in C.

In many (most?) other programming languages (Basic, Pascal and Matlab for example) you typically count from 1 to N, not from 0 to (N-1).

(For example in `for` loops.)

As already said in the other answers there often is the possibility to define the index of the first element of an array freely (e.g. in Pascal) or the index of the first element is even fixed to 1 (e.g. in Matlab).

These languages don't have pointer arithmetic.

**In (theoretical) computer science**

I have no idea if they count from 0 there.

However I think that the programming languages which are used most influence the way of thinking in theoretical computer science, too.

> **Comments:**
> **username_38**: I think the C equivalence of `arr[i]` = `*(arr+i)` follows from its choice of zero-based indexing, not the other way around.  But good point that having pointer arithmetic at all makes zero-based indexing much more natural, and that most still-used languages with 1-based indexing don't have that.  C started as a portable assembly language, so it's totally natural that it works like asm in this regard.  
> **username_44**: @PeterCordes I'm not sure. But I think the fact that the array operator can be used for pointer arithmetic at all (such as `ptr[-5]`) played a role in defining that `ptr[i]` is equal to `*(ptr+i)`.  
> **username_45**: The advantage of zero-based indexing becomes even more apparent when you need to map a 2D matrix to a linear array.  
> **username_46**: This is the missing half of Jorg's answer, which together make the **correct** answer. C made the choice to only support indexing arrays from 0, and after it became popular it influenced the design of a lot of other languages. However, its quite likely *most* languages don't force a 0-based index, and some people thinking this is a computer language thing, (or worse yet, a Computer Science thing) is nothing more than myopia.  
> **username_47**: Most index from 0, including BASIC (though I'm sure there's a variant which starts at 1). [Here's a table](https://www.wikiwand.com/en/Comparison_of_programming_languages_(array)#/Array_system_cross-reference_list).  
> **username_44**: @username_47 Depending on the variant of BASIC arrays start with 0 or 1. However it was typical to start `FOR` loops at 1, not at 0! I just looked into the Acorn Electron manual: Even in BBC Basic (where arrays always started at 0) `FOR` loops were typically starting at 1.  
> **username_6**: @username_45 Not really - that's just an entirely *separate* advantage of zero-based indexing. And rarely needs to be explicit in the external interface anyway - that's just again going back to C's pointer arithmetic fetish. How structures are laid out in memory shouldn't be used to design how they're supposed to be used. If you have code-level abstraction, what's the difference between `matrix[0, 0]` and `matrix[1, 1]`? How does it affect your use of `matrix.ToLinear()`? The interface should be meaningful on its own, separate of its concrete implementation.  

---

### Answer by username_48 on 2018-09-03. Score: 9

In languages such as C, the first item in an array has an offset of zero from the pointer. If the size of your objects are 4 bytes, the next item has an offset of 1 x 4 bytes.
Index   Size    Offset
0       4       base + 0
1       4       base + 4
2       4       base + 8
3       4       base + 12

And so on.
If the items were indexed on natural counting, there would have to be an adjustment made by both the computer and the programmer to find the location of the item in memory. Mistakes would be made by having this additional step, particularly on the human side of the process. It's easier, although slightly unintuitive, to use zero-based indexing.

> **Comments:**
> **username_17**: Welcome to [cseducators.se]! Isn't this just a restatement of OP's third bullet?  
> **username_49**: yes, the pointer (which is the array) contains the 1st element, then you add 1 to get the next element etc. In assembler we were taught indexing to access arrays, so moving to C it all made simple sense.  
> **username_48**: @BenI. My answer addresses the human side of "making it easy".  
> **username_11**: Welcome to the community, please read the question. The OP states in the question that this explanation is unsatisfactory, for the intended audience.  
> **username_6**: Keep in mind that C arrays are rather plain. In many languages, the pointer refers not to the first item, but to things such as the length of the array. And yet both 0-indexed and 1-indexed arrays exist. Indeed, you could use your argument to argue that arrays should start at 1, because that would username_12w you to store metadata in the "0 offset".  
> **username_48**: @username_6 If the metadata is at "0 offset" there's no guarantee it's the same number of bytes as each entry. In reality, it's a packed format: `metadata` + N x `array-item`. Only the `array-item`s are guaranteed to each be the same size. The array part is still 0 based.  
> **username_6**: @CJDennis As surprising as it might sound, plenty of languages older than C didn't have this problem at all - e.g. all arrays had the same element size. C became somewhat famous for encouraging these kinds of hardware-specific optimizations (of course, how effective these turned out to be depended entirely on the programmer). Many considered this to be a step back - instruction-by-instruction performance wasn't thought as an end goal in itself. But regardless, this doesn't change that as soon as you need an offset anyway, 0-based arrays are no longer easier to index than 1-based.  

---

### Answer by username_58 on 2018-09-03. Score: 7

### Simply put, we do not *count* from zero, we *shift* from zero

You can think C as a neat way to *not* write different assembly for every architecture/machine/processor in existence. Instead, take a [simple and short](https://www.bell-labs.com/usr/dmr/www/cman.pdf) macro-like language for a abstracted machine, compile that, and [brk()](http://man7.org/linux/man-pages/man2/brk.2.html) your way on abstracted memory.

But abstracted memory is only a sequence of bytes, you need a way to refer to specific segments. Enter pointers. But to not make every item a username_12cation (think of a string where every char is separately username_12cated) the next step is "lists". The most compact list1 is a pointer to the first element, and then put every other element in adjacent slots.

Every element is, then, indexed as *shift from first*. And because that, the shift *index* starts from zero.

---

1 This is from a era when you need entire reunions to decide if is worth spend whooping **52 bytes** to have [your system](https://pt.wikipedia.org/wiki/The_Mythical_Man-Month) know about leap years...


---

### Answer by username_55 on 2018-09-12. Score: 6

Rather than answer myself based off my personal preference, as all other posters have done, I would instead like to link the following very in-depth analysis instead:

* [Arrays Indexed From One](http://enchantia.com/graphapp/doc/tech/arrays1.html) by Loki Patrick

The conclusion it comes to, is as follows:

> In conclusion, I set out to prove by usage cases which scheme was better: indexing arrays from zero, or indexing arrays from one. I think the discussion has shown that there is no mathematically strong argument that favours one or the other. Every usage case which asserts one scheme is better than another because that other scheme is more awkward can be countered either by a language syntax which ameliorates the problem, or else can be balanced against some other usage cases in which the first scheme is more awkward than the other it is being compared against. There are many data points, and the analysis is complex, yielding *no clear winner*.
>
> However, the thing which tips the balance in my mind is *historical convention* and *interoperability issues*. There are so many existing applications for **zero-based indexing**, and many existing languages which use it, that interoperability and learnability are biased in favour of that camp in my opinion. It is disheartening that the result of an intellectual discussion should be settled with "that's the way we've always done things" but in this case it seems a justified conclusion.
>
> That being said, I think for certain specialised or high-level languages, I hope there is a place for one-based indexing, because I feel it has been an inadequately explored solution to the job of addressing elements of an array. I hope this essay has shown that there are some inherently good things about these schemes, and I also hope that future discussions of the issue won't unnecessarily conflate indexing from one with including end-points in loops or slices; although related, the two are not the same issue.

---

My personal preference is 1-based, because in my experience, the +-1s in 0-based indexing tend to pop up more often in high level logic, while 1-based indexing's +-1s tend to pop up in lower-level code where you need to be paying attention anyway that don't pop up as often in high-level code, leading me to commit notably fewer off-by-one bugs in 1-based languages like Lua.

> **Comments:**
> **username_17**: Nice first contribution here.  Welcome to [cseducators.se]!  
> **username_55**: @BenI. Thanks! :-) As a fan of 1-based indexing, it really pains me when people speak from their personal preference, and I in particular hate Djikstra's very selective argument. I've been lucky to find the resource I linked a while ago, because it is a much better analysis than anything I could hope to do.  

---

### Answer by username_11 on 2018-09-03. Score: 6

I will try to answer, without reference to low-level programming (or any programming language), without mention of history, or much maths.

As already stated in some answers, we do not count from zero (using the value 0 to represent 1, and 1 to represent 2 (Usually)). So what do we do?

We measure from zero. If I give you a ruler, and ask you to measure something, you measure from zero. If I ask you to tell me how far a cell in an array is from the start, then you measure from zero (the first cell is zero from the start: it is at the start), the 2nd cell is 1 from the start.

> **Comments:**
> **username_56**: We absolutely count from zero. If you want to count sheep hopping over a fence, you initialize the `sheep_count` variable to 0, not 1.  If no sheep appear, you must report that zero value as the count.  
> **username_6**: @username_56 That simply isn't true at all. This should be pretty obvious when you take into account that zero-as-a-number is a rather recent invention compared to natural numbers. People always considered "nothing" as a special case, and it took effort to introduce zero to math in a meaningful way (and at the cost of confusions like division by zero). You may have been *taught* to count from zero, but it certainly isn't natural to humans. If you want to count sheep hopping over a fence, do you initialize `cow_count` to zero first? I hope not :)  

---

### Answer by username_57 on 2018-09-07. Score: 6

From time to time I have had to do numerical work in MATLAB and the 1-based indexing always stuck out like a sore thumb, so I have a few examples I can provide where 0-based indexing is advantageous.
Modular access
This is the simplest example. If you want to "wrap around" an array, the modulus operator works like a charm. (And don't say "what if the modulus operator were defined from 1 to n instead"—that would be mathematically ludicrous.)
str = "This is the song that never ends... "
position = 300
charAtPosition = str[position % (str.length)]

Real world examples of this might include working with days of the week, generating repeating gradients, creating hash tables, or coming up with a 
predicable item from a small list given a large ID number.
Distance of zero
In a lot of algorithms and applications, we need to work with distances. Distances can't be negative—but they can be zero. For example, one might want to count how many occurrences there are of each distance in a data set. Indexing from 0 username_12ws this to be handled more naturally. (Even if distances aren't integers—see below.)
Discretisation
Let's say you want to generate a histogram of heights. The first "bucket" is 50cm-70cm. The next is 70-90cm. And so on up to 210cm.
Using zero-based indexing, the code looks like
bucket[floor((height - 50) / 20)] += 1

With 1-based indexing, it looks like
bucket[ceil((height - 50) / 20)] += 1
  or
bucket[floor((height - 50) / 20) + 1] += 1

(the two have slightly different semantics). So you can either have a stray "+ 1" or use the ceil function. I believe the floor function is more "natural" than the ceil function since floor(a/b) is the quotient when you divide a by b; for this reason integer division often suffices in such calculations whereas the ceil version would be more complex. Also, if you wanted the buckets in reverse order, this is 0-based indexing:
BUCKETS = (210 - 50) / 20 - 1

#intuitive because BUCKETS - 1 is the highest index
bucket[(BUCKETS - 1) - floor((height - 50) / 20)] += 1

versus
#not intuitive... what does BUCKETS + 1 represent?
bucket[BUCKETS + 1 - ceil((height - 50) / 20)] += 1
  or
#not intuitive... how come a forwards list needs "+ 1" but
#backwards list doesn't?
bucket[BUCKETS - floor((height - 50) / 20)] += 1

Change of Coordinate Systems
This is related to the above "direction flip". Although I will use a 1 dimensional example, this also applies to 2D and higher dimensional translations, rotations, and scaling.
Let's suppose, for each slot in the top row you want to find find the best fitting slot in the bottom row. (This often occurs when you want to efficiently reduce the quality of some data; image resizing is a 2D version of this).
With 0-based indexing:

#intuitive because the centre of slot[0] is actually at x co-ordinate 0.5
nearest = floor((original + 0.5) / 5 * 7);

With 1-based indexing:

#Why -0.5? Can you explain? And then we need to "fix" it with a +1
nearest = floor((original - 0.5) / 5 * 7) + 1;

Nice Invariants
In order to prove that programs work correctly, computer scientists use the concept of an "invariant"—a property that is guaranteed to be true at a certain place in the code, no matter the program flow up to that point.
This is not just a theoretical concept. Even if invariants are not explicitly provided, code that has nice invariants tends to be easier to think about and explain to others.
Now, when writing 0-based loops, they often have an invariant that relates a variable to how many items have been processed. E.g.
i = 0

#invariant: i contains the number of characters collected

while not endOfInput() and i < 10:

    # invariant: i contains the number of characters collected

    input[i] = getChar()

    # (invariant temporarily broken)

    i += 1

    #invariant: i contains the number of characters collected

#invariant: i contains the number of characters collected

There are two basic ways to write the same loop with 1-based indexing:
i = 1
while not endOfInput() and i <= 10:
    input[i] = getChar()
    i += 1

In this case i does not represent the number of characters collected, so the invariant is a bit messier. (You would have to remember to subtract one later on if you wanted the count.) Here is the other way:
i = 0
while not endOfInput() and i < 10:
    i += 1
    input[i] = getChar()

Now the invariant holds again so this approach seems preferable, but it seems odd that the initial value of i can't be used as an array index—that we are not "ready to go" straight away and have to fix up i first. I suppose it's initially odd for learners of zero-based languages that, after the loop terminates, the variable is one more than the highest index used, but it all follows from the basic rule of "a list of size i can be indexed from 0 to i-1".
I admit that these arguments may not be very strong. That said, off-by-1 errors are one of the most common types of bug and at least in my experience, starting arrays from 1 needs a whole lot more adding and subtracting 1 than 0-based arrays.

> **Comments:**
> **username_6**: You're blinded by what you're used to. `for` loops are looping from `a` to `b`. *Count* is entirely irrelevant! Pascal made this much more explicit in its own loop structures - `for i := 1 to 10` makes this rather obvious. As far as I'm concerned, your code assumes that one variable contains *two* separate meanings that happen to coincide. That's *wrong*; it may be useful for some cases, but you're reusing the same variable to mean two different things. `i` doesn't contain the count because that's it's purpose - it contains it by accident. The same with your buckets example.  
> **username_57**: @username_6 That's the whole point of my post! The multiple meanings don't "happen" to coincide; they are mathematically related, and it is much easier to think about and check for errors if this relation is equal rather than off-by-one. I will admit there are a lot of times where I need to convert array indices to a "1-to-n" system—but almost all of these are to pretty-print things for humans. That is an important consideration—after all, we generally write programs using decimal not hex—however it is also important that code is as easy as possible to review for bugs.  

---

### Answer by username_59 on 2018-09-07. Score: 4

Why not?

Why not count from zero? (This answer is a bit like [username_20's answer](https://cseducators.stackexchange.com/a/5031/1676), but a bit simpler logic than many of the other answers.) Zero is a perfectly valid number. So why not use it? Failing to use that available number is just a waste of the possibility of using that number. You wouldn't want to start lower, since negative numbers may be a bit more complicated to need to consider, and may even be unavailable (when using unsigned numbers). But zero is available, so why waste the possibility of being able to use that number?

If you do that, it's like the 63 SPT (sectors per track/head) limit that contributed to the [504 MiB / 528 MB) Barrier](http://www.pcguide.com/ref/hdd/bios/sizeMB504-c.html). That used a 1-based count. If a zero-based count were used, a limit would have been 512 MB instead of 504 MB. In a day and age when hard drives were counted in megabytes, that limit was nearly 1.6% smaller because someone decided to do a one-based count for one of the numbers. So, keeping that real-world actual cost in mind, what benefit is there to trying to exclude zero? If there isn't one, then don't do it.

Standardizing on one number is nice. When I was ten years old, I knew how to program. Sometimes I counted from one (e.g., "`for(x=1;x<=10;x++)`" ), while other times I counted from zero (e.g., "`for(x=0;x<10;x++)`" ). Sometimes I would mix up those methods, and create a fencepost bug (using "`for(x=0;x<=10;x++)`" ). Later in life, I was pretty strongly compelled to count from zero and drop the test for equality (just testing for inequality using `<`, instead of "less-than-or-equal" using `<=`), and once I got into a standardized habit, I found myself to be far less likely to be making those off-by-one errors.

Ultimately, the code of in many "high level" programming languages is just meant to be converted into "low level" assembly language, which is designed to operate the same way as an actual chip. Zero is kind of a special number (having unique properties with addition and multiplication), while one has less special behavior (having a similar unique property with multiplication, but not addition). So it makes a bit of sense for zero to be special.

Also, if you think of the "what's left", zero is more logical. If you count down ("'for x=10;x;x--)`"), then do you want to exit when there is one job left, or zero jobs left? Zero is more sensible in that particular case, and that may be a key reason why some of the Intel Assembly Language operators perform the way they do.


---

### Answer by username_64 on 2018-09-04. Score: 4

I think it's best to view addresses and indices not as identifying objects or elements, but rather the spaces between or on either side of them.  Thus, an array with four elements would have the following indices:
Addr:   Base+0  Base+1   Base+2  Base+3  Base+4
.         V       V        V       V        V
Indices:  0       1        2       3        4
Elements   [FIRST] [SECOND] [THIRD] [FOURTH]

Each element is associated with two addresses--the one immediately preceding it and the one immediately following it.  The address immediately following any element other than the last will immediately precede another element, and likewise the address immediately preceding any element other than the first will follow another element.  Even though each address other than the first and last will be associated with two elements (one preceding and one following), by convention applying the * operator to an address yields the one following.
Note that unlike the "half-open interval" view, this approach does not require any special handling for pointers that go one beyond the last element.  The address "Base+4" above is associated with the four-element array just like any other, but the * operator cannot be applied to it because that operator would require the ability to compute the next address.

> **Comments:**
> **username_38**: I like this.  This is also a useful way of thinking about labels in assembly language (as zero-width).  Addresses and labels don't have any natural width associated with them; that depends on what type of load/store you do.  (The type system in most languages associates an element width with a pointer, but this is why you can't add/subtract `void*` in C.)  

---

### Answer by username_65 on 2024-01-25. Score: 4

Human counting intuitively revolves around two **different** cases:

1. The total element count in a list or a collection:

   We do so by assigning '1' to the first element and counting upwards (Rarely, we may choose to assign '0' to the first element, as in the floor counting system in the UK where the first floor is called 'Ground floor'). Example: Counting the total apples in a bag by starting the count from 1.
2. The total distance traveled from the first position:

   We do so by assigning a certain value to the starting position, and then adding the offset on it as we traverse a certain distance. Now, what value to assign to the starting position to simplify the calculation? As you might have probably guessed, assigning 0 to the starting position makes calculation much easier. Example: Measuring the distance means keeping the measuring tape such that the "zero" reading is at the starting position. This is what others have pointed out as well.

Let's get to the world of computers. When we talk about the first element of an array being called '0', we are not talking about the element count, but rather the position in the array, just like in the **second case above**. It's essential to recognize this distinction, as our intuition might lead us to compare computer numbering with the first case in human counting. So assigning '0' to the first value of the array simplifies indexing. This means in a computer's memory, the address of the next element can be determined using the offset rule.

While compiler optimizations might have likely been implemented to accommodate this convention, the influence of languages like C, which starts indexing from '0' (unlike FORTRAN that starts from '1'), has solidified this approach. Just like there is no need to alter a measuring tape where the reading starts with 1 instead of 0, even though human brain is already "optimized" (smart) to calculate the distance even if the reading started from 1.


---

### Answer by username_60 on 2018-09-03. Score: 3

I think that one of the first programming languages to use zero-based indexing was BCPL. In BCPL, pointers and integers are interchangable, and arrays are represented by pointers. Subscripting uses the operator `!`, so you can get the first and second members of an array using `A!0` or `A!1`. These are defined to be equivalent to `!(A+0)` and `!(A+1)` where the unary `!` operator dereferences a pointer. It's neat, simple, and consistent, and it wouldn't work with 1-based addressing.

A lot of BCPL ideas were carried into C, and the rest is history.

But although zero-based indexing seems to work best for system programming languages, there are many modern languages that chose to start at 1. XPath is an obvious example. I think the rationale there was that it was expected to be used by non-programmers (e.g document authors) and you can't expect a document author to think of the first chapter in a book as chapter 0.

> **Comments:**
> **username_61**: Indeed BCPL seems to be origin of 0-based indexing. We can try to explain to ourselves or to pupils why indexing starts from 0, but the fact is that it only does so in certain languages, and that most of those do so out of historical reasons. This blog shines some light on the origin of 0-indexing: http://exple.tive.org/blarg/2013/10/22/citation-needed/  
> **username_60**: Nice blog article. I'm amused by the notion that we're more likely to have heard of Eben Upton than of Martin Richards.  
> **username_60**: ... It reflects that the author is clearly digging into software history for the first time and is suprised by his discoveries, thinking that perhaps no-one else knows this. However, his conclusions are a bit inconsistent. Zero based indexing in BCPL was an inevitable consequence of having pointers rather than arrays as the fundamental data structuring concept, it wasn't to make array indexing more efficient.  
> **username_60**: Since we're on Computer Science Educators, I might mention that Martin Richards and Steve Bourne between them probably taught me everything I really needed to know about programming -- mainly by example; they both wrote beautiful code.  

---

### Answer by username_62 on 2018-09-10. Score: 3

Counting is always 100% arbitrary. **Counting from 0, from 1 and from 7 - all make exactly same sense.** Our reliance on indexing from 1 in real life is no different than our reliance on 10 as base of positional system. It's nothing but a convention.

The only issue is "How do I remember where do we agreed to start counting at?". From there comes the lead-on question: "What is the default value for integer variable?" or "If you started with a freshly initialized integer, what would you think would be it's value?"

And this is the reason why we start at 0: **Integers start at 0, so it's helpful to map the first entry of an array to the first value of a variable capable of indexing it.**

> **Comments:**
> **username_6**: BCPL, where zero-based indexing probably originated, didn't initialize variables. So that's hardly the right justification. Also, *integers don't start at 0*. Integers don't *have* a start. As for a default in your favorite language (if it even has one), that's entirely arbitrary - zero is convenient in pre-zeroed memory, but before modern memory management, there were no definite default values. A pretty common practice is to always initialize variables with a meaningful value, rather than some "whateverdefault" - e.g. if you want a control variable that counts down, initialize it with count.  
> **username_62**: @username_6 Yeah, this is what I meant by saying that it's arbitrary. I don't agree with BCPL as the origin. In asm when you think of a memory area as an array, you index it with addr+(0*stride), addr+(1*stride), etc  
> **username_6**: In assembly, you didn't have any abstraction (at first). Indexing an array is already an abstraction - it's a map between "I want the 3rd element of the array" and what's actually needed to get that particular element. The fact that you don't need to know the element size in BCPL (or anything else about the array) is a big difference. Indeed, in assembly, you'd often see very complicated addressing patterns that were tailored to the capabilities of the hardware, rather than the logical structure of the program; in C, if you wanted the next element, you did `element++`.  
> **username_6**: Now, it's true that in C, that actually was a low-level pointer operation. But that's not the purpose of it, that's just a constraint to make the compiler simpler. The meaning is still "the next element" or "the 3rd element", not "pointer + 0x12". C is a rather bare language, but it's still way above the abstraction of then-assembly. Meanings started to creep into things that used to be pure procedural code. Of course, it couldn't compare to anything like LISP - the ties to hardware were far too strong for that. But there were things like `0` as pointer value, or what `i++` means.  
> **username_62**: @username_6 This is why I wrote "when you **think** of a memory as an array". It doesn't matter if the abstraction is a part of a language or your train of thought. BCPL built up on established standards of thinking about a program. I don't really get where are we going, because I feel like you're restating my concepts but phrase them like counter-arguments. If you believe that my answer can be improved, then it appears you need to be more specific.  

---

### Answer by username_63 on 2020-10-05. Score: 3

An example from a non-technical field where counting is universally from 1 and it has strange consequences.

In music, chord intervals start from unision or 1st — that is the two notes sound the same note — and go up 2nd 3rd 4th 5th 6th 7th 8th which is an octave. Thus:

[![Octave intervals](https://i.sstatic.net/Aqnit.jpg)](https://i.sstatic.net/Aqnit.jpg)

Now we go further up from the octave :
9th 10th 11th 12th 13th 14th 15th = 2 octaves

Notice something strange? The 8th of the octave did not double to a 16th of two octaves!

What gives?
The real issue is this:

# An octave has 7 notes!

"Octave" itself is a misnomer!

ie C, D, E, F, G, A, B is the "octave"

After that the "loop" repeats at/from the next C.

And so if we had counted — better measured — the C-C chord — the so-called "unision" — as a zeroth then C-D, a single whole-tone step, would be a first and so on upto C-C being a 7th. And continuing C-(next)C would be a 14th thereby keeping our (arithmetic) expectation intact.

Of course the key as many others have pointed out is that the distance *measured* rather than *counted* between C and itself **is zero!**

# In more Math language

In ℤ {0,1} are special

> The infinite cyclic group (ℤ,+)
> has 0 identity and 1 generator

> The field ℝ (or ℚ) has no generator
> ie 0 remains special, 1 less so.

> **Comments:**
> **username_17**: It gets even weirder when you consider that a second plus a second plus a second is a third, and that you can add unison's (the first) infinitely without ever moving at all.  
> **username_63**: Umm.... Cute observation @BenI. But this is a composition of two different things: the minor one being counting from 1 the major one being the wondrous irregularity of the scale. Which itself we experience through two *big* simplifying approximations: the uncountable infinity of frequencies reduced to (western) music (C# spelt different from Db but the C-D whole tone = D-E whole tone). Then reduced once again to 12 notes of the keyboard  
> **username_17**: Cute observation is what I was going for :)  But it's truly exactly the same observation as octave plus octave is fifteenth, just with smaller numbers.  
> **username_17**: There's also a bit of something not quite right, actually. The octave doesn't have 7 notes; the octave is an interval (so at most, it only has 2 notes), and it is named for being the eighth note along the scale up from the tonic. So I think you meant to say "an octave of a major scale only has 7 notes", but even this wouldn't quite be correct.  It would be correct to say that "an octave of a major scale is comprised of seven notes beyond its initial note".  
> **username_63**: @beni. «but even this wouldn't quite be correct. It would be correct to say that "an octave of a major scale is comprised of seven notes beyond its initial note"» Well there's a programming theorem that every top tested while can be written as a bottom tested do-while. And conversely. I wrote the 7 as CDEFGAB. you could write (reference C) DEFGABC. Which ever way you count there are 7 distinct followed (or preceded) by the "loop"  
> **username_17**: But neither of those is an octave, those notes outline major and minor sevenths, respectively. The octave only has two notes, such as CC.  
> **username_63**: Let me try a different tack @BenI. {a, b, c, d, e, f, g} is a set with 7 elements (cardinality 7). You're not username_12wed 'h' (unless you're German!). In the music world (assuming a fixed scale/mode, no accidentals, modulation and other fancy stuff) **your palette consists of 7 "colours"**  
> **username_17**: Perfect. I agree! This is all correct.  

---

### Answer by username_4 on 2020-05-13. Score: 1

Everything naturally starts at 0. In the beginning, there was nothing. Now, there is all.

You might want to know if you have something or not, and how many as well. It's just easier to say how many.

Also, try counting without 0.  
1, 2, 3, 4, 5, 6, 7, 8, 9
That's only 9 numbers. But if you count 10-19, you have 10 different numbers. 10-20, you have 11. It's easier to just go by the 10s place and group the numbers in tens.


---

### Answer by username_5 on 2018-09-09. Score: 1

There are many answers but I miss an attempt to make it short and comprehensible for non programmers.

> I don't really want to be explaining memory addresses to a new programmer who doesn't understand memory layout and maybe doesn't even understand arrays yet.

A simple and short example.  
We have a list of elements aligned one after the other. The start of this list, the first element is flagged with a pin.  
To get the first element, we go to where the pin is.  
To get the second element, we need to go to the pin **plus one** element.  
Starting at zero the computer can simply calculate where to go from the start location.

More thoughts on that.  
Counting starts with "one" for the first element. Even for programmers. But programmers **don't count** elements when they start at zero, they **give them names**. These names start at the first number that can be built with digits. Zero denotes "nothing" but is the first valid number.

> couldn't a modern compiler often optimize this away?

I think it can't. How? The calculation described above is fundamental, the CPU does it like that. A compiler can't optimize necessary calculations away.

> **Comments:**
> **username_6**: Of course a compiler could optimize this away - this was very common on x86, for example, because of its powerful memory addressing; especially since 486 and Pentium. And of course, just have a look at any modern disassembled code - in most cases, you will not find any direct indexing from the base of the array anyway. Ultimately, in many cases, indexing an array is a relic anyway - for most cases where you see indexing, what you really want is iteration. It's just that many programmers and languages are stuck without distinction between the two.  
> **username_5**: C or many other languages don't have iteration so we really should know what it is and how it works. Modern techniques sometimes are great but sometimes they are simply overcomplicated, less comprehensive compared to [i] and I don't think there is no kind of index accessing behind iterators - we just don't see it any more. So I doubt iterators are really faster than a simple [i].  
> **username_6**: C was deficient in that regard even in comparison with other languages *of its time*. And no, they're certainly not *less* comprehensive. You need to look at code with fresh eyes - a lot of the crazy doesn't seem crazy anymore when you get used to it. The thing about iterators is that any indexing is strictly an implementation detail - which username_12ws you to give much more freedom to the code that's using them as an interface. If you pass an array, it will always be an array. If you pass an iterable, the implementation can do whatever fits - like using a linked list.  
> **username_6**: Iterators can easily be faster than pointers, and they can be slower than pointers. But they're definitely easier to understand and reason about, and they username_12w a lot of optimisations that simply aren't possible with "pointers to an array". Just consider something like map-reduce - it wouldn't be possible if people stuck to the idea that arrays are just a pointer to the first item in an array. Unsurprisingly, it came from the other side of the language spectrum - languages that value abstraction over micro-tweaks.  

---

### Answer by username_7 on 2018-09-10. Score: 1

You give the answer yourself in the third bullet point, and you dismiss it too easily.

Let me delve into my personal experience from when I learned C in the mid-1980s. I remember when for the first I time saw 68k assembler code produced from indexing an array in C and realized that variables are just constant addresses, and indices are just offsets to them, so that addressing an array element `a[i]` could be understood as `*(a+i)` which simply was a readily available adressing mode in machine code if address `a` was already in a register.

It was a revelation on many levels: What C is (a macro assembler with a few bells and whistles plus standard library), what a compiler does, under what constraints programming languages work, and why C was so fast.

Why do you want to deprive your students of this insight? I think teaching arrays (or any programming, really) benefits *tremendously* from teaching memory addresses and some rudimentary assembler, so just go for it. All language abstraction is operating under the constraints of the metal. Your students will never understand why certain seemingly simple things are expensive or impossible if they *don't know what they are actually doing.1*

To sum up, essentially your third bullet point is the reason for the decision by the designers of C (or probably rather, BCPL or B) to start indexing at 0. Saving a subtraction at each element access, i.e. in many hot loops, was certainly highly relvant in 1970. True, *today* these original reasons are largely irrelevant; but today we have 45 years of code and a diverse C-rooted language tree. Regarding these languages we are locked in for good. As Jörg correctly mentioned in another answer, the decision was made differently for many other languages, probably not coincidentally some for which speed is secondary and some who target a lay audience.

---

1Don't get me wrong, I like abstraction. Having had the glimpse under the hood lets me actually appreciate the saftey, correctness and comfort provided by high-level languages and libraries.


---

### Answer by username_8 on 2018-09-03. Score: 1

Slight generalization of CJ Denis's answer: The advantage of zero-based indexing is apparent as soon as you start working with relative indices. If you have a base array A and over it, let's say, a sliding window W, you would have to subtract 1 each time you add W-based index to the A-based one.

> **Comments:**
> **username_6**: And if I add your SSN to my SSN... how does that translate to the array? Indices are a different level of abstraction than "there's 20 bytes after this pointer that represent an array of `short`s". You can argue that (e.g.) C chose this way of representing arrays an indices because of performance targets, but that's about all you can argue about that. A lot of the problems in software engineering stem from this way of thinking that just because it's possible to add two numbers together, it makes sense. It may have it's place in the lowest levels of our systems, but not normal application code.  

---

### Answer by username_9 on 2018-09-12. Score: 1

The technical answer, the one where you explain memory, and the base and index register, should be your preferred method of instructing. I understand that some people think it's daunting, but in reality, it is really straight forward, and it should be the first thing you teach about programming. All of the stack overflows, stack underflows, buffer overflows, null pointer exceptions, dangling pointers, memory leaks, etc are all a lot easier to understand if you start with the basics of what a computer actually does. And you don't need to get super-technical with buses and caches and so on, just enough so that when a memory-related problem happens, they will understand why it happened easier.

As a comparison, which do we teach first in math: addition or multiplication? The reason why is because the latter is a concept built upon the foundation of the former. Teaching what a variable is before teaching what memory is akin to teaching multiplication without ever explaining addition. Everything we do in every computer language that exists on the market to today uses registers and memory. All of them. 100%. To completely gloss over the fundamental basics of computing is to perform a serious disservice to those you are supposed to be educating.

I realize that many modern languages have done away with bare pointers because of their potential for misuse, but that means that the new generation of developers are growing up without understanding a critical part of computers. And pointers are still everywhere, just neatly tucked away behind references, objects, automatic variables, and so on. Which leads to questions about in/out parameters, why changing a value here affected data elsewhere, etc.

Until we have a computer that literally has no concept of a stack, registers, heap/dynamic memory, loops, branches, etc, no matter how far we abstract, at some point, the processor needs to do its thing. And that thing will be done by loading a memory address to a base register, loading an index register, and loading the data from memory as a result of the final calculation. If students do not learn this in class, they will certainly not learn it in the real world in any appreciable amount of time, and will write far inferior code for perhaps the rest of their developer career.

---

Teach your students the basics of computers, and I can virtually guarantee that anyone with sufficient aptitude to be a developer to begin with will never ask the question "why do we count from zero." Once the basics are established, everything else becomes that much easier.

> **Comments:**
> **username_6**: Variables are entirely separate concept from memory; even today, most of the variables you use never make it into memory. As for pointers... pointers are everywhere, yes. Pointer *arithmetic* is a fetish that should have died ages ago. Multiplication *can* be explained in terms of addition, but it doesn't have to. The reason we teach addition first is because it's easy to teach algebraically, while multiplication makes far more sense geometrically - and it so happens that most math teachers are a lot more comfortable with algebra than geometry. But that's an entirely subjective value.  

---

### Answer by username_19 on 2018-09-11. Score: 1

It's not an answer, but it is additional information.

When I was a student, what eventually helped it click for me is that I always found it really annoying and weird that the "19th Century" goes from 1800-1899, and the "20th Century" goes from 1900-1999.

But if we would have started indexing centuries at 0, then the "0th Century" goes from 0-99, the "1st Century" goes from 100-199, ... the "19th Century" goes from 1900-1999, and the "20th Century" goes from 2000-2099.

Likewise – if you're in a place where soccer/football is popular – we typically say the "1st minute" to talk about 0:00–0:59, the "27th minute" to talk about 26:00–26:59, etc. Had we started indexing minutes at 0 instead, the "27th minute" would more logically be 27:00–27:59. (Of course, both of these ignore the additional confusion that the 90th minute is sometimes considered to be 89:00–93:00.)

> **Comments:**
> **username_20**: Actually, not everyone agrees with your first paragraph. Some count centuries starting with year "1" as in 1901 thru 2000. There was a lot of worry about that at the millennium and the danger that systems would fail at the rollover whenever that was. Also, I'll note that the Western calendar doesn't have a year 0. It jumps from 1BCE to 1CE with no 0 in between. Personally, though, The 17th century, being the sixteen-hundreds has always been a pain for me.  
> **username_19**: And then when a student well-actualy's you like that, they fell into your trap and you say, "Wouldn't it make a lot more sense if we started at year 0 and our centuries started at 1900, not 1901? That's 0-indexing." :P  
> **username_20**: Hmmm. Well, actually, I was just pointing out an historical fact.  
> **username_17**: @username_20 Surely that is now anachronistic? I never heard a peep about that when the year 2000 was rolling around. It seemed clear enough at the time that the popular understanding is that the centuries go from '00-'99.  
> **username_20**: Well, see, https://www.scientificamerican.com/article/when-is-the-beginning-of/  
> **username_20**: But the technical issue mostly involved using two bytes for a date's year, so the issue was what happens when 99 becomes 00. The fear was that all date computations would fail and take financial systems (etc.) with them.  
> **username_20**: There were other issues with two digit dates, of course. some people on their 100th birthday were suddenly considered infants and their pensions, etc were put on hold along with some other legal problems. I don't know if you are old enough to remember the web in the previous century, but it was common (nearly universal) for a date form to have two digits for year. You entered your birthday as 7/9/88, for example. That has changed now.  
> **username_11**: So in a race the person in 0th place is the winner (gets the gold). The 1st place gets silver, and the 2nd place gets bronze.  

---

### Answer by username_21 on 2018-09-09. Score: 1

Languages which start from 0 are currently popular but there are others which start from 1. These examples are quite old. Many of the start from 0 languages are derived from or inspired by C.

Cobol is not fashionable now but it is still an important language in business and its arrays start at 1. RPG (not role playing games) also has arrays which start from 1. RPG is ugly and horrible but it is also popular in business. My Fortran is rather rusty but I think that it also started at 1. Very long ago, I used Algol and you could choose the starting index 0, 1, or even negative. For some applications, negative indexes e.g. from -10 to +10, were convenient. I am not sure whether this was a standard feature or just one of the dialect that I used. Things were not so standardised back then.

Edited to remove possible unintended offence.

> **Comments:**
> **username_6**: Pascal and Visual Basic (and many other Basics) also preferred natural indices. Using zero-based indexing really has to do with conflating indexing and pointer arithmetic. If I want an array from -10 to 10, why should I index it from 0, right? Let the compiler/library deal with the details. C didn't have indexing at all, *only* pointer arithmetic, so there was little choice. For some weird reason, even today people still count this as C's *advantage*, rather than misfeature. Oh well.  
> **username_21**: I considered including Basic but it was so long since I have used it that I was not sure.  Also, as you hint, it is probably dialect dependent.  I miss the ability to choose the minimum and maximum index.  It is a shame that it has not caught on.  
> **username_6**: Plenty of languages on the "abstraction makes things easier" side of the barrier still support ranges. You just need to give up C-like languages, for the most part (though e.g. C# does have support for arbitrary indexing, it's not really "equal citizen" compared to zero-based).  

---

### Answer by username_10 on 2018-09-11. Score: 0

There are several explanations. But I would say that the main reason is because the number in computer science represents a memory offset i.e. the physical distance from the beginning of the memory.

0 then means "no distance from the beginning of the memory" that is, the start.

> **Comments:**
> **username_11**: I 100% agree. When I saw this answer for the 1st time, I was totally convinced. However this is not the first time that this answer has been given, and **some** of the older versions, give deeper explanations.  

---

### Answer by username_12 on 2018-09-12. Score: 0

You are starting with the first element of you index set.

In a math text, your index set usually is $\mathbb{N}\setminus\{0\}$, because this is how you normally count.

But in your PC you use an unsigned integer type as index set. And the **first** element of this ordered set is the number $0$, not the number $1$.

So the problem is your number type. You could have a natural-number datatype without zero for your index and everything would be fine. But we like to re-use existing data types used for arithmetic, which normally need to have a $0$, which comes before the $1$.


---

### Answer by username_13 on 2018-09-23. Score: 0

Modern computer implementations (physical, CMOS, as well as most virtual machines) almost completely use only binary logic (although some flash memories may use more than 2 states per physical bit cell).

By convention, if you have 1 bit of binary information, or a single logic signal, there are two possible states, and we call one state “0” and the other state “1”. If that 1 bit addresses 2 bits of memory, then the two addresses are 0 and 1 to match the binary state nomenclature of the address bit.

Early TTL Logic data books labeled the signal state nearest 0 Volts as logic “0” in the truth tables.

Compositions of a small number of logic bits (more than one) are usually numerically interpreted as sums of powers of two times those binary bits, and the minimum unsigned sum is zero.

Many early programming languages (assembly) grew out of shortcuts for data and program entry via binary switches. The conventions followed. Lots of binary zeros sum to numeric zero. And you count up starting from there.

If you are a CS educator, you should not be teaching computation as magic, but as the result of the implementation of comprehendable binary logic.

> **Comments:**
> **username_14**: This is merely moving the question to: why is binary using 0/1 and not 1/2  

---

### Answer by username_15 on 2018-09-12. Score: 0

Very simple:  This is the offset of the address.  So if an array called x is located with x at say 0x1000, an array that start's there has its first element x[first] at 0x1000
By using:
 0 as [first]

there's no math to compute it's start, and it is computationally efficient.

> **Comments:**
> **username_11**: I 100% agree. When I saw this answer for the 1st time, I was totally convinced. However this is not the first time that this answer has been given, and some of the older versions, give better explanations.  
> **username_15**: As pointed out, other earlier answers mention this, but it is a concise explanation, "in my own words" IMHO.  

---

### Answer by username_16 on 2018-09-13. Score: 0

username_1s answer pretty much nails it, and looking at an index as an offset to a memory address (as username_15 and others suggest) gives a precise technical reason. However, there is something I'd like to add:

It is a great tragedy that we don't "count" from zero in our everyday life. That is because early humans didn't have a concept of *zero*. That concept was unfortunately introduced much too late. We naturally use a decimal system because of our ten fingers (we also use a base 5 system for stroked lists, with the diagonal stroke representing a thumb). We should actually use a base 11 system, because we can display not ten, but eleven states with our hands: 0 fingers up to 10 fingers up.
So if only the concept of zero had evolved earlier in the history of mankind, "counting" from zero would feel perfectly natural to us (and Matlab wouldn't start indexing at 1).

> **Comments:**
> **username_11**: I am not sure that I agree, with all of paragraph 2 (counting from zero), but the base 11 thing is spot on. Why did I never see this. I am going to use base 11 from now on (or at least for a week). Oh no I failed already, I write eleven in base 10. I should have written 10 (that is eleven in base 10). Yes that is what I will do. I will use base 10 from now on.  

---

### Answer by username_14 on 2022-05-04. Score: -1

We count from 1 because we started counting before the zero was invented.

We should have all switched to the new, lowest digit when it was invented but this habit was impossible to kill so we stuck to 1.

The revolution that came with the zero is called <https://en.wikipedia.org/wiki/Positional_notation>, also known as "place-value". Positional notation username_12wed us to *re-use the same digits* to count tens, hundreds, thousands, etc. If you pay attention, you'll notice that tens, hundreds and thousands all start with the new, lowest digit: zero. But for units it was too late; too hard to change.

However many programming languages *did* the switch and count all digits from zero because keeping units special and different from all other digits creates irregularities and edge cases; see examples at <https://en.wikipedia.org/wiki/Zero-based_numbering#Numerical_properties> and in some of the other answers here.

> **Comments:**
> **username_17**: This is a weird and false history.  Counting from 1 still *exists* because it is useful in many contexts. The question you are responding to is about why counting from zero is useful in *this* context.  
> **username_14**: Which exact fact is false @BenI.? You don't say. Counting from zero is useful in any context, Intelpedia gives many examples unrelated to computers.  
> **username_17**: The second article you linked to makes one generalized mention of the problems with zero-based numbering, though since it's an article about the benefits, it isn't a surprise that it doesn't speak more to it.  Zero-based counting is excellent for distances (such as arrays) and its analogs, but disusername_12ws the ordinal and cardinal count to match.  If you have index zero, you now have one element, and that mismatch is permanent.  And if you have zero elements, then the question of index becomes undefined....  
> **username_17**: ... Sometimes we want distance measuring, sometimes we want ordinal and cardinal to match, such as when we are counting eggs in an egg container.  Both systems have their use and their place.  
> **username_17**: You intimate a history in which habit, not clear usefulness, is the reason that standard counting is still around, and it's simply not true.  Every school in the world teaches traditional counting to small children, and children everywhere learn that most people have ten fingers, and learn how to count them so that they *arrive at that number.*  It's a big benefit, and should not be discounted.  
> **username_14**: So you don't think we counted from 1 before zero was invented?  
> **username_17**: We did, I don't contend that you are wrong about everything.  The false history is the part where you say that we kept standard counting because of "habit" instead of "usefulness".  Both systems are useful.  
> **username_14**: "Both systems have their use and their place" - you're justifying habit better than I would ever have.  
> **username_17**: Even in programming, no programming language has removed the standard count.  It would be nonsensical to use positional notation for the size of an array, and we don't, ever.   When your maximum index is [0] (positional counting), your list size is 1 (standard counting, which also matches the maximum ordinal number).  If we all "switched over" you list size would now be zero if your only position was zero, and you would no longer be answering the question "how many items are in this list", because that is not a positional question.  
> **username_14**: You're very very close. I've never seen someone explaining pure convention so well while falling so short of realizing it's just convention. Fascinating.  
> **username_17**: **Person 1:** *holds up an apple* How many apples am I holding?  **Person 2:** Zero.  **Person 1:** *puts down the apple* How many now?  **Person 2:** an undefined number.  If that conversation sounds useful to you, then this conversation probably isn't.  

---

### Answer by username_18 on 2018-09-08. Score: -3

"Thing zero"

I have nothing, I have one thing, I have two things...

0,1,2...

0x00, 0x01, 0x02...

0000, 0001, 0010...

There is nothing in my register, there is one thing in my register, there are two things in my register.

There is nothing in my array, there is one thing in my array, there are two things in my array.

If you started at one, you'd always have a minimum of one thing.

> **Comments:**
> **username_17**: But myint[0] isn't nothing, it's something.  

---

