Leap year tester

ddanbe 0 Tallied Votes 176 Views Share

Although the DateTime structure in .NET has an IsLeapYear method. Lots of people in here like to do this on their own.
See this snippet on how it can be done. This is in C# but other language adepts might benefit from it also.

using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Leap year tester.");
            Console.WriteLine();
            Console.WriteLine("The year {0} is a leap year = {1}.", -57, IsLeapYear(-57));
            Console.WriteLine("The year {0} is a leap year = {1}.", 0, IsLeapYear(0));
            Console.WriteLine("The year {0} is a leap year = {1}.", 632, IsLeapYear(632));
            Console.WriteLine("The year {0} is a leap year = {1}.", 666, IsLeapYear(666));
            Console.WriteLine("The year {0} is a leap year = {1}.", 999, IsLeapYear(999));
            Console.WriteLine("The year {0} is a leap year = {1}.", 1302, IsLeapYear(1302));
            Console.WriteLine("The year {0} is a leap year = {1}.", 1400, IsLeapYear(1400));
            Console.WriteLine("The year {0} is a leap year = {1}.", 1600, IsLeapYear(1600));
            Console.WriteLine("The year {0} is a leap year = {1}.", 1952, IsLeapYear(1952));
            Console.WriteLine("The year {0} is a leap year = {1}.", 2002, IsLeapYear(2002));
            Console.ReadKey();
        }

        static bool IsLeapYear(int year)
        // A year is a leap year if it is divisible by 4.
        // If it is also divisible by 1OO, 
        // it can only be a leap year if it is divisible by 400
        // With the use of the remainder, conditional AND and OR operators
        // the above can be expressed in on line of code.
        {
            if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
                return true;
            else
                return false;
        }
      

    }
}