Hello,

I saw some loops examples that uses something like

while (i%5 ==0)....

what is the % for or mean? I am new to java.

thanks

Printable View

- 02-06-2011, 07:38 AMcurioustoknowloops
Hello,

I saw some loops examples that uses something like

while (i%5 ==0)....

what is the % for or mean? I am new to java.

thanks - 02-06-2011, 07:54 AMZack
It's the modulus operator, which finds the remainder of a number when divided out into the second number.

So let's say you start with this: 7%2. To determine its value, you take 7, and subtract 2 until you cannot anymore. Like so:

7 - 2 = 5

5 - 2 = 3

3 - 2 = 1

(Can't subtract 2 anymore, since 1 - 2 < 0)

Therefore, 7%2 == 1. You'll also notice if you do long division for 7 divided by 2, the remainder will be 1. This holds true for any modulus operation.

In your case, basically it's checking to see if "i" is divisible by 5. That meas 5, 10, 15, ..... etc.

For more information:

Modulo operation - Wikipedia, the free encyclopedia

The Remainder or Modulus Operator in Java

modulus computing - Google Search

Good luck! - 02-06-2011, 08:02 AMcurioustoknow
so the following example case2 is just checking if the year is divisible by 4,100 and 400? I dont understand why are we doing this?

for (int m=1; m<=12; m++)

{

String monthN="";

int numD=0;

switch (m)

{

case 1:

monthN="January ";

numD=31;

break;

case 2:

monthN="February ";

if ((yr%4 == 0 && yr%100 != 0) || yr%400 == 0 )

numD=29;

else numD=28;

break;

case 3:

monthN="March ";

numD=31;

break; - 02-06-2011, 01:45 PMj2me64