Leap year tester

Please support our C# advertiser: Intel Parallel Studio Home
ddanbe ddanbe is offline Offline Mar 30th, 2009, 11:53 am |
0
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.
Quick reply to this message  
C# Syntax
  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:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC