 LOOPS | SoloLearn: Learn to code for FREE!

0

# LOOPS

int x = 1; while (x++ < 5) { if (x % 2 == 0) x += 2; } Could someone explain what the part in the brackets does? isn't x%2=1 ?

+7

Yes you are right, values that pass the condition is 2 and 4. Others are failed because 1 and 3 are not divisible by 2. It is same as, if(x%2==1){ continue; }else{ x+=2; }

+7

Razvan Tivadar i think you are confuse with 4,5 as answer.just look here at this code int x = 1; while (x++ < 5) { if (x % 2 == 0) x += 2; Console.WriteLine(x); //4 //5 } The hole confusion is in the missing curlybraces of the if condition. First x is = 1 that x is compared to 5 that's become true and x is increase by 1 and become 2. Second, the condition run and x%2==0 become true cause x is 2.and x+=2 runs x is now 4 and it prints 4. Third, 4(x) is now comperd to 5, four is less than 5 so condition become true loopruns x is now 5. Fourth, in condition x%2==0 become false because x is now five. And because of the if condition did not have braces print functions is also a part of loop rather than just if statement.So in the last 5 got printed. I think this helps.

+5

int x = 1; while (x < 10) { if (x % 2 == 0){ x += 2; Console.WriteLine(x); } x++; } This is more secure

+2

+1

Well the number of results is correct (2) but when i run the code it gives me 4 and 5

+1

But then it wouldn't respect the condition <5 right?

+1

Ok thanks, i was just asking because it was in the quiz

+1

But i don't get why the values have to be divisible by 2