Okay, so I was solving one of the Euler problems, and I came across a rather peculiar doubt... Till now, I had thought that:
1 2 3
for (i=1; i<=max; i++)
if (some condition)
do something;
And
1 2
for (i=1; i<=max && some condition; i++)
do something;
would be equivalent, (and in a way, the latter be speed efficient in nested loops, since I'd check the condition before executing the loop for a certain value of i). However, I came to realize it is not so.
Can someone please explain why these two are not equivalent?
The difference is that in the first one some condition has nothing to do with when the loop ends, and in the second one, it does. They're not equivalent.
Here's a very simple example; let's say that some condition is "i is an even number", for example.
1 2 3
for (i=1; i<=max; i++) // For all values from i=1 to max...
if (some condition) // if it's an even number....
do something; // do something
This will cycle over all i from 1 to max, and do something will happen many many times.
1 2
for (i=1; i<=max && some condition; i++) // For all i from i to max, but stop when i is an even number...
do something;
In this case, do something will not even happen once, as the very first check will find that some condition is false.
Ooooh, now I get it.. So in the for loop, when the condition evaluates to false, it exits the for loop, and does NOT re-iterate, is that correct? Dunno why such a silly thing did not strike me... So dumb of me...