Write a program in C# using Linq that prints count of leap years in 20th century ?

 Posted by Nagasundar_Tn on 11/29/2012 | Category: C# Interview questions | Views: 5412 | Points: 40

We have to note that they are not asking to print all the leap years, but they are asking only the number of leap years. Now 20th century means the years between 1900 and 1999. Here the code :

class Program

public int NoOfLeapYear()

int cntYears = (from year in Enumerable.Range(1900, 100)
where DateTime.IsLeapYear(year) == true
select year).Count();
return cntYears;

static void Main(string[] args)
Program pObj =new Program();
Console.WriteLine(string.Format("No of LeapYear between 1900-1999 is {0}",pObj.NoOfLeapYear()));
catch (Exception exx)

In the NoOfLeapYear function I am using Enumerable.Range() method to get all the values between the specific range. Enumerable.Range() method accepts two parametes. In which first parameter is the starting number and second parameter indicates count.

Here important point to be notes is
Enumerable.Range(1900, 100)

this code will return the value from 1900 to 1999. Starting first value as 1900 the 100th value is 1999. These are the years of 20th century.
In "where" condition I am using Leap year functio of DateTime class and checking for every year between 1900 and 2000.
In Select statement I am using Count() to get the total number. Since Count() return integer I declared "cntYears" as Integer. (No type casting required).

The output of above code is
No of LeapYear between 1900-1999 is 24

Asked In: In my preivous interview | Alert Moderator 

Comments or Responses

Login to post response