0

Multiple conditions in for loop

Trying to test why don't multiple conditions give correct answer. My code for the question "print even numbers from 10 to 20 in Java" is ... ... for(byte a=10; a<20 && a%2==0;++a){sout(a);} Gives me 10, initialized value of 10. Why is that. Please see that I can reach desired output work following code ... ... for (a=0;a<20;a+=2){System.out.println(a)}

10th Jan 2020, 11:32 PM
Saad Mansoor
Saad Mansoor - avatar
6 Réponses
+ 6
Your condition a<20&&a%2==0 actually means this: 'Please run this loop as long as a is lower than 20 and a is divisible by 2.' This stops to be true with 11.
10th Jan 2020, 11:36 PM
HonFu
HonFu - avatar
+ 2
Why don't you put the condition inside the loop itself? for(int i = 10; i <= 20; i++) { if(i % 2 == 0) { System.out.println(i); } }
10th Jan 2020, 11:40 PM
HNNX 🐿
HNNX 🐿 - avatar
+ 1
Thank you I understand now.
10th Jan 2020, 11:38 PM
Saad Mansoor
Saad Mansoor - avatar
+ 1
Mirielle🐶 yes, and I've already mentioned that in question. Guess that's the right solution since using 'if' will cause more process to run hence code is less cleaner and processor will consume more power.
10th Jan 2020, 11:46 PM
Saad Mansoor
Saad Mansoor - avatar
0
'if' was not allowed. But yes it could be reached using that.
10th Jan 2020, 11:41 PM
Saad Mansoor
Saad Mansoor - avatar