A year that has 366 days (with an extra day in February) is called a LEAP YEAR. A leap year will be the 4th year after a leap year, 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.
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"