- 1

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 ?

4th Mar 2020, 5:11 PM
Razvan Tivadar
Razvan Tivadar - avatar
9 Respostas
+ 8
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.
4th Mar 2020, 6:56 PM
0_O-[MĂ€gĂĄr_SĂĄm_ÄkĂ _NĂŒllpÞïntĂȘr_ÈxĂ«cĂ©ptïön]~~
0_O-[MĂ€gĂĄr_SĂĄm_ÄkĂ _NĂŒllpÞïntĂȘr_ÈxĂ«cĂ©ptïön]~~ - avatar
+ 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; }
4th Mar 2020, 5:21 PM
0_O-[MĂ€gĂĄr_SĂĄm_ÄkĂ _NĂŒllpÞïntĂȘr_ÈxĂ«cĂ©ptïön]~~
0_O-[MĂ€gĂĄr_SĂĄm_ÄkĂ _NĂŒllpÞïntĂȘr_ÈxĂ«cĂ©ptïön]~~ - avatar
+ 5
int x = 1; while (x < 10) { if (x % 2 == 0){ x += 2; Console.WriteLine(x); } x++; } This is more secure
4th Mar 2020, 6:25 PM
0_O-[MĂ€gĂĄr_SĂĄm_ÄkĂ _NĂŒllpÞïntĂȘr_ÈxĂ«cĂ©ptïön]~~
0_O-[MĂ€gĂĄr_SĂĄm_ÄkĂ _NĂŒllpÞïntĂȘr_ÈxĂ«cĂ©ptïön]~~ - avatar
+ 2
Thanks a lot :)
4th Mar 2020, 7:40 PM
Razvan Tivadar
Razvan Tivadar - avatar
+ 1
Well the number of results is correct (2) but when i run the code it gives me 4 and 5
4th Mar 2020, 5:33 PM
Razvan Tivadar
Razvan Tivadar - avatar
+ 1
But then it wouldn't respect the condition <5 right?
4th Mar 2020, 6:17 PM
Razvan Tivadar
Razvan Tivadar - avatar
+ 1
Ok thanks, i was just asking because it was in the quiz
4th Mar 2020, 6:34 PM
Razvan Tivadar
Razvan Tivadar - avatar
+ 1
But i don't get why the values have to be divisible by 2
4th Mar 2020, 6:34 PM
Razvan Tivadar
Razvan Tivadar - avatar
+ 1
Ok
5th Mar 2020, 2:56 PM
Teekay
Teekay - avatar