w3resource logo
C# Sharp Programming Exercises

C# Sharp Exercises: Find the leap years between to specified years

C# Sharp DateTime : Exercise-28 with Solution

Write a C# Sharp program to find the leap years between 1994 and 2016.

Note : Use IsLeapYear method.

Sample Solution:-

C# Sharp Code:

using System;

public class Example28
{
   public static void Main()
   {
      for (int year = 1995; year <= 2016; year++)
      {
         if (DateTime.IsLeapYear(year))
         {
            Console.WriteLine("{0} is a leap year.", year);
            DateTime leapDay = new DateTime(year, 2, 29);
            DateTime nextYear = leapDay.AddYears(1);
            Console.WriteLine("   One year from {0} is {1}.", 
                              leapDay.ToString("d"), 
                              nextYear.ToString("d"));
         }         
      }
   }
}

Sample Output:

1996 is a leap year.                                                                                          
   One year from 2/29/1996 is 2/28/1997.                                                                      
2000 is a leap year.                                                                                          
   One year from 2/29/2000 is 2/28/2001.                                                                      
2004 is a leap year.                                                                                          
   One year from 2/29/2004 is 2/28/2005.                                                                      
2008 is a leap year.                                                                                          
   One year from 2/29/2008 is 2/28/2009.                                                                      
2012 is a leap year.                                                                                          
   One year from 2/29/2012 is 2/28/2013.                                                                      
2016 is a leap year.                                                                                          
   One year from 2/29/2016 is 2/28/2017. 

C# Sharp Code Editor:

using System;

public class Example28
{
   public static void Main()
   {
      for (int year = 1995; year <= 2016; year++)
      {
         if (DateTime.IsLeapYear(year))
         {
            Console.WriteLine("{0} is a leap year.", year);
            DateTime leapDay = new DateTime(year, 2, 29);
            DateTime nextYear = leapDay.AddYears(1);
            Console.WriteLine("   One year from {0} is {1}.", 
                              leapDay.ToString("d"), 
                              nextYear.ToString("d"));
         }         
      }
   }
}

Improve this sample solution and post your code through Disqus