0
C# the while loop last question
I need help. int x=1; while (x++ < 5) { if (x%2 == 0) x+=2 } I really don't understand. I calculated it myself and it turned 3 but it's not the answer. Someone pls help.
2 Answers
0
Nevermind. I got what was going on.
Basically in the code when the if happens the ++ in the condition of the while statement increased x which means this:
x=1
while (1++ <5)
1 is used and then incremented for the rest of the code in while statement.(x++)
so it goes:
if (2%2==0) which is true
2+=2 which equals 4
now that 4 goes back up due to loop
while (4++ <5)
4 is used then gets incremented, becomes 5
if (5%2==0) false so the statement in if command doesn't get executed
5 gets back up.
while (5++ <5) 5<5 is false so the loop stops being executed.
i literally had to use the playground,type in the question and when i got the answers i realised what happened in the code. If anyone sees this, i hope it helps if you are getting stuck like i did.
+ 8
int x=1;
while (x++ < 5)
{
if (x%2 == 0)
x+=2
}
First loop, 1 smaller than 5 is true, x incremented by 1. x is now 2.
2%2 == 0 is true, x += 2. x is now 4.
Second loop, 4 smaller than 5 is true, x is incremented by 1. x is now 5.
5 % 2 == 0 is false. x is still 5.
5 is smaller than 5 is false, x incremented by 1. Loop ends.
Loop runs twice. Final value of x should be 6.