Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading