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:

Re: help explaining small loop

Re: help explaining small loop

Re: help explaining small loop

So, everything clear now?

db

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.

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...?

Re: help explaining small loop

thank you Xero and Tolls. I'm looking into it now as I've been super busy.

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

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++;

Re: help explaining small loop

repped. you guys rock.

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