if and for condition statements

Feb 12, 2012 at 6:57pm
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?

Thank you in advance... :)
Feb 12, 2012 at 7:04pm
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.
Last edited on Feb 12, 2012 at 7:11pm
Feb 13, 2012 at 11:38am
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...

Thank you so much! :)
Topic archived. No new replies allowed.