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)}
6 odpowiedzi
+ 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.
+ 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);
}
}
+ 1
Thank you I understand now.
+ 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.
0
'if' was not allowed. But yes it could be reached using that.