A year that has 366 days (with an extra day in February 29 days, usually 28 days) is called a LEAP YEAR. A leap year is coming after 3 normal years ie., the 4th year after a leap year will be the other one. Here, we are explaining how to check whether the given year is a leap or not.
Leap year check can be implemented very simply using nested if .. else condition
in R programming. First, we will ask the user to enter a year for leap year checking. R provides readline()
function for taking the user's input by prompting an appropriate message to the user for data using 'prompt
'.
Here the user is asked to enter a year, data will be stored to a variable named year. Then, check the given year can be divided by 4, If the remainder is zero it is a leap year otherwise not a leap year. Also, check the given year is a century (eg., 2000) dividing the year by 100 without any remainder; then divide the year by 400 and check whether the remainder is 0, if that condition is also satisfied then it is a leap year, and if not means it's a normal year.
Let's understand with some examples,
Consider the year 2004, it is completely divided by 4 and thus it is a leap year. If we take 2005 it is not fully divided by 4 and thus it's not a leap year.
Now check examples of the century years, we should satisfy an extra condition for century ie., for a century being leap year we should also divide it by 400 and check any remainder left. Consider the year 2000, it can be divided by 4 and let's confirm it is a century as dividing 2000 by 100 and then to check for leap year divide by 400. Here 2000 is a century and a leap year, but if we take 1900 it will satisfy the first 2 conditions but won't divide by 400 and thus it's not a leap year.
STEP 1: Read a year prompting appropriate messages to the user using readline()
into variable year
STEP 2: First look for a century, use nested if condition
to check year is exactly divisible by 4,100,400 and gives a remainder of 0;
print
The year is a leap yearprint
The year is not a leap year STEP 3: If a year is divisible by 4 but not by 100 means year is not a century then print
The year is a leap year
STEP 4: If a year is not divisible by 4 then print
The year is not a leap year
year = as.integer(readline(prompt="Enter a year: "))
if((year %% 4) == 0) {
if((year %% 100) == 0) {
if((year %% 400) == 0) {
print(paste(year,"is a leap year"))
} else {
print(paste(year,"is not a leap year"))
}
} else {
print(paste(year,"is a leap year"))
}
} else {
print(paste(year,"is not a leap year"))
}
Enter a year: 2011 [1] "2011 is not a leap year" Enter a year: 2004 [1] "2004 is a leap year"