R Program to check for leap year

How to check the given year is a leap year or not

Here we are explaining how to write an R program to check the given year is a leap year or not. We can use the readline() function to take input from the user (terminal). Here the prompt argument can choose to display an appropriate message for the user.

How leap year check is implemented in R Program

We are using readline() function for taking the user’s input. Given below are the steps which are used in the R program to check leap year. In this R program, we accept the user’s input into the variable year by providing an appropriate message to the user using ‘prompt’. Check the given year is a leap year by dividing the year by 4, 100 and 400 and check the remainder. If the remainder is zero it is a leap year otherwise not a leap year.

ALGORITHM

  • STEP 1 : prompting appropriate messages to the user
  • STEP 2 : take user input using readline() into variables year
  • STEP 3 : check if year is exactly divisible by 4, 100 and 400 gives a remainder of 0
  • STEP 4 : if remainder is a non-zero print year is not a leap year.
  • STEP 5 : if remainder is zero print year is a leap year.

R Source Code

year = as.integer(2014)
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"))
}
## [1] "2014 is not a leap year"

R Source Code

year = as.integer(2020)
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"))
}
## [1] "2020 is a leap year"