# loops

• 02-06-2011, 08:38 AM
curioustoknow
loops
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, 08:54 AM
Zack
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.

Modulo operation - Wikipedia, the free encyclopedia
The Remainder or Modulus Operator in Java

Good luck!
• 02-06-2011, 09:02 AM
curioustoknow
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, 02:45 PM
j2me64
Quote:

Originally Posted by curioustoknow
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?

with if ((yr%4 == 0 && yr%100 != 0) || yr%400 == 0 ) the code is calculating if the year is a leap year and if true the number of days in the month FEBRUARY is 29.