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,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,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(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"