for(int i=0; i<number.length-1; i++){
System.out.println(number[i]);
}
Should be
// no '-1'
// V
for(int i = 0; i < number.length; i++) {
System.out.println(number[i]);
}
Why?
Let's see what happens if there are 5 elements in the array, then they are indexed as follows:
0, 1, 2, 3, 4
If we use i < 5-1
(or i < 4
), once i
becomes 4, before the next iteration of the loop runs, it will stop, skipping the last index.
In case the above doesn't explain it, note the order in which things happen in a for-loop:
- First the initialization occurs
- Then the following is repeated until the condition is false:
- The condition is checked
- A loop iteration is run
- The increment happens
The most applicable part here is that a loop iteration will never run if the condition is false.