Reputation: 20862
folks,
I am adding a logic expression in the for loop and it is not behaving as I expected. Could you shine some light on me? Thanks very much.
The following code works fine
for (i=0;i<N;++i)
if (a[i] == 1){
....
}
and I tried to write it this way, it seems the for loop is fully skipped.
for (i=0;i<N && a[i]==1;++i){
....
}
What is wrong with the 2nd way?
Upvotes: 0
Views: 168
Reputation: 318
You never enter the loop if a[0] != 1. That's a condition for your for loop to be executed just like how i < N is too.
Upvotes: 0
Reputation: 49363
This code:
for (i=0;i<N;++i)
if (a[i] == 1){
Means, increment i
, starting from 0, keep going until it's greater than or equal to N
, for each element in a[]
check to see if it's equal to 1
This code however:
while(i < N && a[i] == 1)
Says loop as long as i
is less than N
and a[i]
is equal to 1. So as soon as either of those condtions is false it will break from the loop.
Upvotes: 0
Reputation: 129314
The loop continues while the condition is true. Remember that a for-loop for(A; B; C)
can be replaced with [conceptually]:
A;
while(B)
{
...
C;
}
So, you have:
i = 0;
while(i < N && a[i] == 1)
{
...
i++;
}
So, if at the first instance a[i] is not 1, then you never enter the loop, and just go to whatever comes after. It's probably not what you wanted to do, which is why it's not doing what you wanted... ;)
Upvotes: 4