Read-only forum archive

For loop with multiple conditions (boolean expr)

For loop with multiple conditions (boolean expr)

vinay · Tue Jan 11, 2022 9:37 am

The following two similar codes are giving different outputs.

The following code:
Code:
for (i=1;i<=10;i++)
{
    if ((i%2)!=1)
    {
        i;
    }
}

returns the expected answer, whereas the code
Code:
for (i=1;i<=10  && (i%2)!=1;i++)
{
    i;
}

returns nothing.

Is this expected behaviour?

-- VInay

Re: For loop with multiple conditions (boolean expr)

hannes · Thu Jan 13, 2022 2:18 pm

Yes, it is:
a for loop stops at that moment that the condition is not fulfilled:
this is here the case already for the start value of i: 1:
it is smaller than 10, not i%2 is not !=1: combined with &&: condition is false.
What you probably mean:
Code:
for(i=2;i<=10;i+=2)
{
  i;
}

Re: For loop with multiple conditions (boolean expr)

vinay · Sun Jan 16, 2022 12:05 pm

Thank Hans, got it! Didnt think of the trick:
Code:
i+=2


-- VInay