Home Programs How to check whether a year is a leap year or not in C#

How to check whether a year is a leap year or not in C#

In this example we will show to check if a year is a leap year in C#

There is a basic formula for this

To determine whether a year is a leap year, follow these steps:

  1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
  2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
  3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
  4. The year is a leap year (it has 366 days).
  5. The year is not a leap year (it has 365 days).

Example

 

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int myYear;
            Console.Write("Input an year : ");
            myYear = Convert.ToInt32(Console.ReadLine());

            if ((myYear % 400) == 0)
                Console.WriteLine("{0} is a leap year.\n", myYear);
            else if ((myYear % 100) == 0)
                Console.WriteLine("{0} is not a leap year.\n", myYear);
            else if ((myYear % 4) == 0)
                Console.WriteLine("{0} is a leap year.\n", myYear);
            else
                Console.WriteLine("{0} is not a leap year.\n", myYear);
            Console.ReadLine();
        }
    }
}

Here are a couple of test runs

Input an year : 1992
1992 is a leap year.

Input an year : 2000
2000 is a leap year.

Input an year : 2022
2022 is not a leap year.

You may also like