Question from exam:
Write a Boolean expression for the following: A is a leap year.
Any help would be appreciated!
Question from exam:
Write a Boolean expression for the following: A is a leap year.
Any help would be appreciated!
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.
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
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.