Is it necessary to start variable from zero (var i = 0
) of any looping ? When should I use var i = 1;
and when var i =0;
?
2
You can start a loop at whatever you want. The reason you see loops starting at zero often, is because they are looping through an array. Since the first item in an array is at index ‘0’, it makes sense to start looping from 0 to access every item in an array.
You should use i = 0 in situations where iterating starting at zero would be natural, as previously stated this could include array indexing or similar. Personally I would say I use this style at least 90% of the time, as when modelling problems in the computer we mold them to use built in data structures, which usually start at 0. Our minds become use to working in this style.
Starting at i = 1 is more natural for modeling many problems while designing algorithms. For example, if you are given a problem such as person 1 is x years old, person 2 is y years old, and so on, indexing using the given numbers may make it easier to give an answer if asked something such as who is the youngest person in the list. Experience and experimentation will teach you if this is worthwhile, in my experience, this can be helpful in things such as programming competitions (like the ICPC), where algorithms must be developed quickly with not much time for debugging, and the algorithms can be very complex, so the clarity is important.
In other words it may be beneficial to waste this first index if it adds clarity, however experienced programmers quickly learn to understand both styles.
However, if you start at zero, remember to be aware that the arrays still start at zero, and you will need an n + 1 size array to represent n elements if you use indexing starting at 1.
Also be aware of your conditional in the for loop.
for (int i = 0; i < 10; i++) – Will loop 10 times
for (int i = 1; i <= 10; i++) – Will loop 10 times
It is basic, but a common source of errors that may be hard to track down, especially for beginning programmers.
Indexing at 1 will often feel more natural and intuitive as you think of the first element as element “1” so you will want to create an array that is one-based
.
Over time you will find that most data structures, methods and programming routines that you work with treat arrays as being zero-based
.
I found, over time that making zero based arrays work for my “1 equals 1” 1 based
mental model meant that I was frequently doing thing like index+1 or index-1 or otherwise messing around with it to make it work with a zero based array.