+ 1

What will be the values of x and y after execution and how many times the loop will execute? Can someone explain step by step?

$x=0; $y=0 for($x=1; $x<=5; ++$x) $y= $x++; --$y;

26th Feb 2018, 5:44 PM
Sarbjot Kaur
Sarbjot Kaur - avatar
2 Respuestas
+ 1
x will be 7 and y will be 4. the --$y; will only be executed after the for loop, at least I assume so because I don't see any {} the loop will start with $x = 1 because 1 <= 5 is true. $y gets the current value of $x, then $x gets post-incremented. So: $y=1 and $x=2 The loop continues with $x=3 because x is pre-incremented with ++$x in the loop condition. Again $y will get $x's current value, which is 3. Then $x will be post-incremented again. $y = 3 and $x = 4 $x gets incremented before the execution of the code again, thus being $x = 5, $y gets the current value again and $x gets incremented afterwards. $y=5 and $x = 6 $x gets incremented and the loop checks if $x is smaller or equal than 5, which is false because $x is 7 at this point. The for loop ends because the conditions aren't met. Then $y gets pre-decremented, immediately changing it's value to 4. I hope this is understandable and that I could help you :)
27th Feb 2018, 10:30 AM
Kai Schlegel
Kai Schlegel - avatar
0
What is the value of y after this code runs? x, y = [1, 2] x, y = y, x Answer :- 1
29th Jun 2020, 6:43 AM
Gourav Tomar
Gourav Tomar - avatar