Home > Back-end >  How does this loop work? I am unable to understand it
How does this loop work? I am unable to understand it

Time:11-01

for(int i=1;i<=n;){
    f  ;
    if((i  ==p) || (i  ==p))
        break;
}

example1 : n=7,p=3,f=0; so the value of f should be 1, right? But it is giving f=2 as output

example2 : n=7,p=4,f=0; it is giving output as f=2

example3 : n=7,p=5,f=0; it is giving output as f=3

Help me understanding this.

CodePudding user response:

Case 1 When n=7,p=3,f=0 . Lets look at values of different variables while going through the for loop.

Iteration 1

for(int i=1;i<=n;) //here n = 7
{
   f  ; //here f becomes 1 that is now we have f = 1
   if((i  ==p) || (i  ==p)) // variable i is incremented by 1 and becomes 2 because of the 
   //first i  . But note the old value of i(which is 1) is returned by i  . So although 
   //right now i = 2, its old value(which is 1) is compared with the value of variable 
   //p(which is 3). Since 1 and 3 are not equal the next (i  ==p) is evaluated. And so 
   //again variable i is incremented and becomes 3. But here also the old value of 
   //i(which is 2) is used to compare with value of variable p(which is still 3). But since
   //2 is not equal to 3 the control flow doesn't go inside the `if` and so `break` is not 
   //executed.

   break;
}

Iteration 2

for(int i=1;i<=n;) //here n = 7
{
   f  ; //here f becomes 2 that is now we have f = 2
   if((i  ==p) || (i  ==p)) // Now i is incremented again because of the first i   and 
   //becomes 4. But here also the old value of variable i(which is 3) is used to compare 
   //with value of variable p(which is 3) and since 3 = 3 the condition is satisfied 
   //and we go inside the `if` statement and `break` is executed. Note at this point 
   //the value of f is 2 .That is why you get f =2 as output.

   break;
}

Similarly you can work out for Case 2 where n=7,p=4,f=0; .

Note that you can/should use the debugger for this purpose.

  • Related