+ 2
The while loop
I am a beginner. Please can someone help me with this question? In Step by step How many times will the following loop execute? int x = 1; while (x++ < 5) { if (x % 2 == 0) x += 2; }
6 Answers
0
It will execute 2 times.
+ 5
https://code.sololearn.com/cnHUBEsZ6mNh/?ref=app
Please try it with code and print statements
X start with one
While x++ < 5
gives x the value 2
Now
X % 2 == 0 is true
That makes x have the value 4
While x++ < 5 is true
And x gets the value 5
X% 2 == 0 is false ( the answer is 1)
While x++ < 5 is false
The were 2 iterations
+ 2
x=1
Iteration 1:
x++<5 here it is first compared x value then next x++ is evaluated so 1<5 is true, and x++ so x=2 now
next x%2==0 =>2%2==0 true so x+=2 =>x=x+2=2+2=4
Iteration 2:
4<5 true, and x++ then x=5
5%2==0 false.
Iteration 3: 5<5 false, loop stops further execution.
[ But x++ is executed since it part of condition, so x=6]
So it iterates only 2 times...
For more read about post/pre fix expression evaluation...
+ 1
While loop will execute two times and for loop execute one times
As we know while loop firstly check condition then execute statement
Initial value of x is 1 it check 1<5 then it have post increament i.e x++ now value of x is 2 then it then control teansfer to if statement if statement check 2%2==0 or not if true execute and return the value if not then return to again while loop becz if statement execute within while loop
but 2%2==0 true so it execute
now value of x is 4 it again goto while loop and check 4 < 5 or not it agin true then x increament now value of x is 5 now if condition goes to false so it not execute again go to while loop and check 5 < 5 this time false so while loop willn't execute
Above statement conclude that while loop execute two times but if loop execute only one times I hope my logic correct
0
Kandane Arachchige Dona Malinka hey! First of all the value of X starts with 1 as per the condition X will be 2 and 2<5 so condition is true then 2%2==0 the condition is true and if statement gets executed then again loop starts now the value of X will be 4 (X+=2.....X=2+2=4) and 4<5 condition is true and if checks the condition 4%4==0 if statement will execute and again loop starts with the value X=6 and 6<5 condition is false then loop stops and finally the loop will execute twice .
I think now you understood the conceptđ if you've any query then you can ask me with mentioned in the comment