944,018 Members | Top Members by Rank

Ad:
  • C# Code Snippet
  • Views: 4710
  • C# RSS
0

Leap year tester

by on Mar 30th, 2009
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.
C# Code Snippet (Toggle Plain Text)
  1. using System;
  2.  
  3. namespace ConsoleApplication2
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. Console.WriteLine("Leap year tester.");
  10. Console.WriteLine();
  11. Console.WriteLine("The year {0} is a leap year = {1}.", -57, IsLeapYear(-57));
  12. Console.WriteLine("The year {0} is a leap year = {1}.", 0, IsLeapYear(0));
  13. Console.WriteLine("The year {0} is a leap year = {1}.", 632, IsLeapYear(632));
  14. Console.WriteLine("The year {0} is a leap year = {1}.", 666, IsLeapYear(666));
  15. Console.WriteLine("The year {0} is a leap year = {1}.", 999, IsLeapYear(999));
  16. Console.WriteLine("The year {0} is a leap year = {1}.", 1302, IsLeapYear(1302));
  17. Console.WriteLine("The year {0} is a leap year = {1}.", 1400, IsLeapYear(1400));
  18. Console.WriteLine("The year {0} is a leap year = {1}.", 1600, IsLeapYear(1600));
  19. Console.WriteLine("The year {0} is a leap year = {1}.", 1952, IsLeapYear(1952));
  20. Console.WriteLine("The year {0} is a leap year = {1}.", 2002, IsLeapYear(2002));
  21. Console.ReadKey();
  22. }
  23.  
  24. static bool IsLeapYear(int year)
  25. // A year is a leap year if it is divisible by 4.
  26. // If it is also divisible by 1OO,
  27. // it can only be a leap year if it is divisible by 400
  28. // With the use of the remainder, conditional AND and OR operators
  29. // the above can be expressed in on line of code.
  30. {
  31. if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
  32. return true;
  33. else
  34. return false;
  35. }
  36.  
  37.  
  38. }
  39. }
Message:
Previous Thread in C# Forum Timeline: Office 2003 PIA's for Windows Vista
Next Thread in C# Forum Timeline: hey what's up.....? NEED ur Help Here





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC