Leap Year or not in R Programming Language

Leap year or not in R Programming Language

A leap year is a year that is evenly divisible by 4, except for years that are divisible by 100. However, years divisible by 400 are considered leap years again. In simpler terms:

  • If a year is divisible by 4 and not divisible by 100, it is a leap year.
  • If a year is divisible by 100 and not divisible by 400, it is not a leap year.
  • If a year is divisible by 400, it is a leap year.

Let’s now write a simple R program to check if a given year is a leap year

Input:

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 1:

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

Output 2:

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

Conclusion:

In conclusion, a leap year is determined by specific rules related to divisibility by 4, 100, and 400. The R program presented here encapsulates these rules within a function called isLeapYear. The user is prompted to input a year, and the program then checks whether it is a leap year or not using the defined function. Leap years are crucial for keeping our calendar synchronized with the Earth’s revolutions around the Sun. Understanding how to programmatically check for leap years is a useful skill for various applications, including date and time calculations in programming.

Scroll to Top