+ 4

Explain how we get 2 for below c++ program int x=0; for(int z=0;z<5;z++){if((z>2)&&(++x>2)){x+=7;}} cout<<x;

for z=0 we get x=1. z=1 then x=2 z=2 then x=3. z=3 then x=4 then we enter into if block and we get x=11 for z=4 we get x=12 and also we enter into if block there we get x=19 for z=5 we left the if loop and print the x then obviously I think that x is 19 but how we get 2 here I had a major doubt in this question anyone can explain this question????

21st Jun 2017, 10:47 AM
siva leela
5 Respuestas
+ 1
&& will evaluate the second expression only if the first expression is true, as "False&&Stmt" will always be "False" irrespective of the value of Stmt So for z=0,1, and 2, the value of x will be unchanged. For z=3 it will perform ++x to get x=1, but it still won't go inside the if as 1>2 is false. For z=4 again ++x gives x=2, 2>2 is false, so it doesn't go into the if statement. When z=5 it will exit the loop as the condition is z<5.
21st Jun 2017, 11:04 AM
Anil Kamath
+ 1
Hey just follow this z=0: nothing happens to x z=1: nothing happens to x z=2: nothing happens to x z=3: here z>2 but ++x (i.e x is 1) is less than 2 z=4: here z>2 but again ++x (i.e x is 2) is not greater than 2 z=5: loop is completed now x is 2
21st Jun 2017, 10:56 AM
Vighnesh Reddy
Vighnesh Reddy - avatar
+ 1
when z>2 is false ++x is not increment and when z=3,4 and then ++x execute 2 time now the value of x is 2 and and z executed 5 time hope you got my point
21st Jun 2017, 10:58 AM
Anjani kumar jha
Anjani kumar jha - avatar
+ 1
and(&&) does not check the 2 condition unless 1 condition is true btw the brackets eg-(1st cond.&& 2nd cond.) so at last x=2
21st Jun 2017, 11:36 AM
Abhishek Mittal
Abhishek Mittal - avatar
0
if you want to get x = 19 - change IF conditions in some places. when (z>2) is true - && will not evaluate the second expression
21st Jun 2017, 11:20 AM
Ренат Мухаметшин
Ренат Мухаметшин - avatar