Introduction
According to Wikipedia, Leap year is a year containing one additional day in order to keep the calendar year synchronized with seasonal year.
Conditions to call year as leap year:
Condition1: Divisible by 400. For example: 1200,1600, 2000 are leap years.
Condition2: Not divisible by 400 and 100 but Divisible by 4. For example: 2002, 2008,2012,2016 are leap years.
Using the above 2 conditions, we will write a program to check whether user input year is leap year or not.
Program:
namespace DotNetMirror
{
class ClsIsLeapYear
{
private static void Main(string[] args)
{
int year;
Console.Write("Enter any year:");
year = Convert.ToInt32(Console.ReadLine());
if (FnIsLeapYear(year)) //if ((year % 4 == 0) && (year % 400 == 0 || year % 100 != 0))
{
Console.WriteLine("{0} is a leap year.", year);
}
else
{
Console.WriteLine("{0} is not a leap year.", year);
}
Console.ReadLine();
}
public static bool FnIsLeapYear(int year)
{
if (year % 4 != 0) //400 and 100 divisible by 4 So check for not condition first
{
return false; //Not divisible by 4
}
else if (year % 400 == 0)
{
return true; //divisible by 400 (condition 1)
}
else if (year % 100 == 0)
{
return false; //divisible by 100
}
else
{
return true; //Not divisible by 400 and 100 but Divisible by 4 (Condition 2)
}
}
}
}
If you feel FnIsLeapYear method implementation is bit difficult to understand, you can use simpler condition like
if ((year % 4 == 0) && (year % 400 == 0 || year % 100 != 0))
Program Output:
Input: 2012
Output: 2012 is a leap year.
Input: 2013
Output: 2013 is not a leap year.
Input: 2000
Output: 2000 is a leap year.
Alternative:
DateTime.IsLeapYear(2012) - True
DateTime.IsLeapYear(2013) - False