Using != with counter controlled loops
c++, java
Solution
as other answers have shown, `while(i < 100)` is safe`*`, `while(i != 100)` is precise`**`.
As an aside, you may want to try `while(i++ < 100)` or `for(i = 0; i < 100; ++i)` instead of the simpler while loop you have shown--forgetting to increment the counter at the end of the loop is a real pain. Note that, if `i=0`, `i++` will equal 0, and then increment i for next time, and `++i` will increment i and then equal 1, so for `while(i++ < 100)`, the postfix ++ operator is necessary.
Also note, that if `i` was 0 when it got tested in the condition, then it will be 1 in the loop body (for the while example), so if `i` is an index for an array or something, and not just keeping track of loop iterations, you'd be better to stick with just a for loop (which increments i after each iteration).
`*`: safe here meaning less likely to enter an infinite loop. It is also unsafe in that it can hide potential errors, if the loop isn't trivial
`**`: precise in that if it doesn't do exactly what you expect it to, it will fail, and you will notice. Some other answers have also described how to protect you from errors even more in this kind of loop.
Problem
Last question for today all...I will get back with tomorrow..I have a lot to follow up on... I am looking in Reilly Java text- talking about counter controlled loop patterns..(does not matter what language..) The author for counter controlled loops (for, while, etc) and with nesting loops...uses the != for test...Now I realize != is used for certain situations with event controlled loops-like sentinel or EOF type of loops- but to me- using it with a counter controlled loop is a bad idea...very prone to errors.. Examples: ``` x = 0; while (x != 100) { y = 0; while (y != 100) { ... y++; } x++; } ``` Would it be better to just say..using the other relational operators... ``` x = 0; while (x < 100) { //or even better some defined constant... y = 0; while (y < 100) { ... y++; } x++; } ``` Which from what I have seen is usually the way presented in texts..classes.etc.. Once again- would all you considered this bad- or just a different way of doing it... Thanks...