# help explaining small loop

• 02-12-2012, 08:26 PM
derb2k2
help explaining small loop
public static void main (String[] args)
{
int num = 1, max = 20;

while (num < max)
{
if (num%2 == 0 )
System.out.println (num);
num++;
}

}

this is the output when i run it :

2
4
6
8
10
12
14
16
18

how is the output in a +2 pattern?

also, I'm a little confused by (num%2 == 0 ) loop. To start off, it would read ( 1%2 == 0 ). How is the inner loop executed considering the math? 1 / 2 = 0.5 . Isn't the decimal portion(.5) the remainder and thus .5 =/= 0?? :frusty:
• 02-12-2012, 09:08 PM
DarrylBurke
Re: help explaining small loop
• 02-13-2012, 12:53 AM
derb2k2
Re: help explaining small loop
:=-:
• 02-13-2012, 07:40 AM
DarrylBurke
Re: help explaining small loop
So, everything clear now?

db
• 02-13-2012, 07:07 PM
XeroXen
Re: help explaining small loop
The result of the output comes from your if statement, you are only printing numbers where the num variable % 2 == 0.

The % sign represents modulus division, which returns the REMAINDER of the division problem (essentially, you do division to the nearest whole number, and you return the remainder). So, 3 % 5 would return 2, because 3 / 5 in integer division returns 1, and there is a remainder of 2.

In this case, you are doing modulus division by two in order to determine if the number is a divisor of 2, in which case the remainder would be 0. Therefore, any number that is divisible evenly by two is printed, and the other numbers are not.

I hope that helped.
• 02-13-2012, 07:11 PM
Tolls
Re: help explaining small loop
Quote:

Originally Posted by derb2k2
also, I'm a little confused by (num%2 == 0 ) loop. To start off, it would read ( 1%2 == 0 ). How is the inner loop executed considering the math? 1 / 2 = 0.5 .

It's not a loop.
It's an 'if' statement.
Quote:

Originally Posted by derb2k2
Isn't the decimal portion(.5) the remainder and thus .5 =/= 0?? :frusty:

Exactly, which in an 'if' statement would mean...?
• 02-14-2012, 01:55 AM
derb2k2
Re: help explaining small loop
thank you Xero and Tolls. I'm looking into it now as I've been super busy.
• 02-14-2012, 02:09 AM
derb2k2
Re: help explaining small loop
ahah. Man, I'm so dumb. I see it now. I made a mistake in reading the code if that's possible with this small fragment of code.

if (num%2 == 0 )
System.out.println (num);
num++;

question: the "num++" operation is executed regardless of the (num%2 == 0) condition right?

thank you guys for the help
• 02-14-2012, 04:52 AM
pbrockway2
Re: help explaining small loop
Yes the increment occurs whether or not the print took place.

For this reason many people (ie me and all others I consider to be right thinking) use braces: even with one line blocks.

Code:

```if(num % 2 == 0) {     System.out.println(num); } num++;```
• 02-14-2012, 02:31 PM
derb2k2
Re: help explaining small loop
repped. you guys rock.

hopefully i can start getting a good grip on java. :(party):