Savage99 Savage99 - 1 year ago 80
Java Question

Having an issue between < and <=

My question is the following, I've noticed that sometimes in the following code you need to use a < and sometimes its <=.

count < numbers.length
count <= numbers.length

Do we only use the <= if it is length()???

Answer Source

< would allow count to go up to numbers.length - 1 (inclusively)

<= would allow it to go up to numbers.length (again, inclusively)

Usually when iterating over an array etc., you use < a.length if you want to iterate from 0 (i.e. for (i=0 ....) ) and <= a.length if you start from 1 (i.e. for (i=1 ...)).

Either choice is fine, so long as you remain consistent throughout your program. Note that starting from 0 to < length is usually the practice preffered.