shri cool
shri cool

Reputation: 95

How does this code produces an output of 6 and 3?

#include<stdio.h>
void main() {
     int x = 0,y = 0,k = 0;
     for(k = 0; k < 5; k++){
         if(++x > 2 && ++y > 2)    x++;
     }
     printf("x = %d and y = %d",x,y);
}

I'm not able to understand how the above piece of code generates x = 6 and y = 3.

RESOLVED : I didn't know that when there is &&, if the first statement evaluates to false the second will not be executed.

Upvotes: 0

Views: 298

Answers (4)

keep_smiling
keep_smiling

Reputation: 29

&& is the short-circuit operator.

if ( ++x > 2 && ++y > 2 )

in this if statement the second operand will be evaluated only if the first one is true.

  1. when k=0 X will be incremented by 1. Now x value is 1. x > 2 is false. So Y won't increase.
  2. When k=1 X will be incremented by 1 . Now X value is 2 . X > 2 is false. So Y won't increase.
  3. when k=2 X will be incremented by 1 . Now X value is 3 . X > 2 is true . So Y will be incremented by 1 . Now Y value is 1 . but Y > 2 is false . So total if condition is false.
  4. when k=3 X will be incremented by 1 . Now X value is 4 . X > 2 is true . So Y will be incremented by 1 . Now Y value is 2 . but Y > 2 is false . So total if condition is false.
  5. when k=4 X will be incremented by 1 . Now X value is 5 . X > 2 is true . So Y will be incremented by 1 . Now Y value is 3 . Y > 2 is true . So total if condition is true. Then X will be incremented by 1.
  6. The final answer is X=6 and Y=3 .

Upvotes: 1

pmg
pmg

Reputation: 108938

&& is a short-circuit operator.

The first time through the loop, only ++x is evaluated.
The second time through the loop, only ++x is evaluated.
The third time through the loop, both are evaluated.
...

Upvotes: 4

gsamaras
gsamaras

Reputation: 73366

Not related to your question, but please read What should main() return in C and C++? int.


enables short circuit, and && is an operator that follows that. So, this:

if(++x > 2 && ++y > 2)

says:

  1. Increment x by 1.
  2. If x is greater than 2 (thus the first operand of && is true), evaluate the second operand.
  3. The second operand says to increment y by 1, and if y > 2 is true, then the whole if condition will be true.

Your code is equivalent to this:

#include <stdio.h>
int main() {
     int x = 0, y = 0, k = 0;
     for(k = 0; k < 5; k++){
         x = x + 1;
         if(x > 2)
         {
             y = y + 1;
             if(y > 2)
             {
                 x = x + 1;
             }
         }  
     }
     printf("x = %d and y = %d", x, y);
     return 0;
}

Upvotes: 3

Sunil Hirole
Sunil Hirole

Reputation: 239

if(++x > 2 && ++y > 2)

In this line if first condition is false it will not evalute second condition. So first condition is false until value of x is 3

Upvotes: -1

Related Questions