Post new topic Reply to topic  [ 3 posts ] 
Author Message
 Post subject: For loop with multiple conditions (boolean expr)
PostPosted: Tue Jan 11, 2022 9:37 am 

Joined: Sat Oct 01, 2005 11:40 am
Posts: 40
Location: IIT Guwahati, Guwahati, Assam, INDIA
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


Report this post
Top
 Profile  
Reply with quote  
 Post subject: Re: For loop with multiple conditions (boolean expr)
PostPosted: Thu Jan 13, 2022 2:18 pm 

Joined: Wed May 25, 2005 4:16 pm
Posts: 275
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;
}


Report this post
Top
 Profile  
Reply with quote  
 Post subject: Re: For loop with multiple conditions (boolean expr)
PostPosted: Sun Jan 16, 2022 12:05 pm 

Joined: Sat Oct 01, 2005 11:40 am
Posts: 40
Location: IIT Guwahati, Guwahati, Assam, INDIA
Thank Hans, got it! Didnt think of the trick:
Code:
i+=2


-- VInay


Report this post
Top
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

You can post new topics in this forum
You can reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

It is currently Fri May 13, 2022 10:53 am
cron
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group