+ 2
Can somebody explain me how we get 2 as output of this code? :)
2 Answers
+ 3
Here, I'll try breaking it down to the best of my abilities -
1. An int x is. declared with a value of 0
2. A for loop is entered, with its primary variable being z which has a value of 0
3. z is less than 5, so the statements within the loop are run
4. The if statement is run, and because z is not greater than 2, it is immediately exited
5. The for loop is run again twice, with z incrementing once each time and the if statement being exited immediately
6. z is now equal to 3, resulting in the second condition in the if statement to be run, as z is now greater than 2
7. The incremented value of x is evaluated to see if it is greater than 2, which it is not
8. The if statement is exited, and the for loop runs again with z now being equal to 4
9. The if statement is run one last time, once again incrementing x and checking its value to see if it's greater than 2
10. It evaluates to false, and because z is now not less than 5, the for loop is exited
11. The value of x is printed, outputting 2
Hope this helped!
+ 1
yeah! i get it now. i thought that no matter the fact that first condition is false, that the second one will run. tnx bro!