-10

Question from exam:

Write a Boolean expression for the following: A is a leap year.

Any help would be appreciated!

John P. Lally
  • 43
  • 3
  • 11

4 Answers4

8

A year is a leap year if it is divisible by 4 and not divisible by 100, but it is always one if it is divisible by 400. You can translate this to code literally:

int year = 2004;
boolean leap = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);

The modulo operator (%) gives you the remainder when dividing the numbers, so it is equal to 0 if the first number is divisible by the second.

As Bathsheba points out, this only works for the Gregorian Calendar (our modern system since 1582 in some countries or even later in others), if you want to handle years prior to this date, the code would be much more complicated and it would require some research for the exact rules at that time. In an exam, however, you should not need to worry about those.

pascalhein
  • 5,700
  • 4
  • 31
  • 44
  • 2
    Even more brownie points if you point out that this is only the case for the Gregorian calendar. In the Julian calendar leap years were, in error, every 3 years. Oops. – Bathsheba Jul 23 '14 at 13:38
  • Note that non-conformist England didn't adopt Pope Gregory's calendar until 1782. – Bathsheba Jul 23 '14 at 13:41
  • @Bathsheba: added that to my answer. Since the OP mentioned an exam, I assumed that it the question is only about the Gregorian Calendar, and the rules before it were more complicated anyway. – pascalhein Jul 23 '14 at 13:41
  • I just get on my high horse as soon as anyone starts talking about dates and calendars :-) – Bathsheba Jul 23 '14 at 13:42
0

http://en.wikipedia.org/wiki/Leap_year

from article pseudo code:

if year is not divisible by 4 then common year
else if year is not divisible by 100 then leap year
else if year is not divisible by 400 then common year
else leap year
firegnom
  • 833
  • 7
  • 20
0
 if((A%4==0) && A%100!=0)||A%400==0)
sagar
  • 106
  • 2
  • 8
0

You can use this boolean function to determine a leap year:

public static boolean IsLeapYear(int year)
      {
         if ((year % 4) == 0)
         {
            if ((year % 100) == 0)
            {
               if ((year % 400) == 0)
                  return true;
               else
                  return false;
            }
            else
               return true;
         }
         return false;
      }

This follows the two rules to determine a leap year

First Rule: The year divisible by 4 is a leap year. Second Rule: If the year is divisible by 100, then it is not a leap year. But If the year is divisible by 400, then it is a leap year.

Adam H
  • 561
  • 1
  • 9
  • 20
  • But the exam question wants an *expression*, not a function. – Bathsheba Jul 23 '14 at 13:45
  • Then I would of got no points for the answer. As an expression `boolean isLeapYear = ((year % 4 == 0) && year % 100 != 0) || year % 400 == 0);` – Adam H Jul 23 '14 at 13:52