R Program to check if given year is leap year or not


February 4, 2023, Learn eTutorial
2459

What is a leap year? How do we check for leap year?

 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. 

  • If a year given is divisible by 4 without any remainder means it's a leap year, otherwise not.
  • If the given year is a century (years ending with 00) then it should also be divisible by 400 otherwise, it's not a leap year

How to solve this leap year program using R?

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.

ALGORITHM

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;

  • If yes print The year is a leap year
  • else print 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 

R Source Code

                                          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"))
}
                                      

OUTPUT

Enter a year: 2011
[1] "2011 is not a leap year"

Enter a year: 2004
[1] "2004 is a leap year"