DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

.NET Program to check Leap Year or Not

By Ashok Nalam on 26 Jun 2013 | Category: C# | Tagged: datetime .NET 
The proram checks whether user input year is Leap Year or Not.
  Discuss Add Comment   |  
Add rating Rate this resource   

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:

Using .NET Framework DateTime.IsLeapYear Method, we can know year is leap year or not.

DateTime.IsLeapYear(2012) - True
DateTime.IsLeapYear(2013) - False
  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 8666  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (1)
 
1. By Neha Renge on 01 Oct 2017

Explin with in any one example plz