I wrote an array search:

for (int i=0; i<N; i++) { if (array[i] == foo) { write('Элемент найден'); } else { write('Элемент не найден'); } } 

But for some reason, as a result, the element is found and not found at the same time. How can this be?

The problem is consistently reproduced with any programming language, any massive data structure, and any form of loop, including jquery each.

  • For the sake of interest, do such questions really come across as often? - Fat-Zer
  • @ Fat-Zer I saw four. - Pavel Mayorov

1 answer 1

The problem is that the conditional operator is executed more than once - but a lot, once for each iteration of the loop. And each time one of the branches is selected, so the conditional operator is arranged.

Therefore, inside the loop it is impossible to conclude that the array element is not found. This conclusion can be made only after the cycle ends!

The easiest way to correct the algorithm is if a piece of code is in a separate subroutine (function) - just add the output from the function inside the "positive" branch, then any code after the end of the cycle can be executed only if the element is not found:

 for (int i=0; i<N; i++) { if (array[i] == foo) { write('Элемент найден'); return; } } write('Элемент не найден'); 

In a more complicated case, an additional Boolean variable (flag) is needed to preserve in it the fact that an element is found:

 bool found = false; for (int i=0; i<N; i++) { if (array[i] == foo) { write('Элемент найден'); found = true; break; } } if (!found) { write('Элемент не найден'); } 

Sometimes it happens that the sign "not found" can be hidden in already existing variables and not start a new one:

 int foundIndex = -1; for (int i=0; i<N; i++) { if (array[i] == foo) { foundIndex = i; break; } } if (foundIndex >= 0) { write('Элемент найден'); } else { write('Элемент не найден'); } 

Finally, in Python, there is another way to do this - the else branch of the cycle:

 for item in array: if item == foo: print('Элемент найден') break else: print('Элемент не найден') 

This works because the else branch of the loop is executed if the cycle has reached the end and has not been interrupted by the break statement.