For Loop conditional increment

I just playing around and got doubt on this.

We have an array, where we need to find and replace all the even numbers with 99.

If found, the number isn't even, then increment the index and check the next number, until last index.

My Approach:

int[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for(int index = 0; index < data.length;) {
  if(data[index] % 2 == 0) {
    data[index] = 99;
  }
  else index++;
}

However, it seems to loop through all the numbers, even if condition is true.

Like, take an example of the second number '2'.

As 2 is even, it shouldn't go to the else condition and incements the index, however it does!!!

I'm not really sure about why it's being doing this. Please guide.


There is no reason for your index++ statement to be conditional. This might lead in some cases to infinite loop.

The only reason your code doesn't result in an infinite loop is that you change each even number to an odd number. Then, when you check that number again in the next iteration of the loop (since you didn't increment the index), you'll find that it's odd, and this time increment the index.

Your loop will have 15 iterations instead of just 10.

You can see this if you add a System.out.println (index); as the first statement of the loop. The output you'll get is:

0
1
1
2
3
3
4
5
5
6
7
7
8
9
9

It will make more sense to just change the logic to:

int[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for(int index = 0; index < data.length; index++) {
  if(data[index] % 2 == 0) {
    data[index] = 99;
  }
}