# Interger Checking in C

1. Nov 7, 2009

I am making a program in C to tell the user what day of the week at date will be (eg. 1st Jan 2000 is a Saturday).
I need to account for leap years, the rule for them is below.

All years divisible by 4 are leap years unless the year can be divided by 100. There is, however, an exception to this 100 year rule exception. Any year that can be divided by 400 is a leap year. So while the years 1700, 1800 and 1900 were not leap years because they are divisible by 100, the year 2000, because it is divisible by 400, was a leap year.

I can devide the year 2001 by for and get 500.24, but how can I know that its not a interger?

2. Nov 7, 2009

### CompuChip

The simplest is to check whether division by 4 produces a remainder. The operator you want is "%":

2000 % 4 == 0
2001 % 4 == 1
2002 % 4 == 2
2003 % 4 == 3
2004 % 4 == 0
etc.

3. Nov 7, 2009

### Staff: Mentor

2001/4=500 if you use integers, and 500.25 if you use floats.

4. Nov 7, 2009

### technoweasel

If you are unfamiliar with typecasting [ like "(int)" ] you might want to look into that, although your current problem seems to be solved.

5. Nov 7, 2009

I found something on type casting (I had a lecture on it last week...)
if (year/4 == (int)year);

I forgot the remainder operator even existed.
Thanks for the help guys.

6. Nov 8, 2009

### Staff: Mentor

No idea what was your plan, but that would not check if the year is leap.

8/4 = 8 ?

7. Nov 8, 2009

### CompuChip

You could check whether the float division gives the same answer as the integer divison. I.e., something like

(float)year/4.0 == (float)((int)year/4)

However, this is ugly (the modulo operator makes it immediately clear what is meant) and risky (the float division of 2001/4 may give 500.2499999 while the integer division cast to float gives 500.250000..., and the comparison fails).

8. Nov 8, 2009

No that code worked, I tested it out. It checks if year would go into a int, if its true the if statement will run.

9. Nov 8, 2009

### CompuChip

Sure it works.
But you can shorten it to
if(year == 0);

10. Nov 8, 2009