R Program to Check for Leap Year

A leap year is a year that contains an extra day, February 29th, making it 366 days long instead of the usual 365 days. Leap years are necessary to keep our calendar in sync with the astronomical year. In the Gregorian calendar, which is the most widely used calendar system today, leap years occur in years that are divisible by 4, except for years that are divisible by 100 but not by 400. This article discusses how to write an R program to determine whether a given year is a leap year or not.

Concepts:

Leap Year Criteria: A year is a leap year if it meets the following criteria:

  1. It is divisible by 4.
  2. If it is divisible by 100, it must also be divisible by 400.

Examples:

Leap Years (Divisible by 4 and not by 100, or divisible by 400):

2016: Divisible by both 4 and not divisible by 100, so it's a leap year.

2020: Divisible by both 4 and not divisible by 100, so it's a leap year.

Non-Leap Years (Divisible by 100 but not by 400):

1800: Divisible by 100 but not divisible by 400, so it's not a leap year.

1900: Divisible by 100 but not divisible by 400, so it's not a leap year.

Leap Years (Divisible by 4 and 100 and 400):

1600: Divisible by both 4, 100, and 400, so it's a leap year.

2400: Divisible by both 4, 100, and 400, so it's a leap year.

Steps:

  1. Accept the input year from the user.
  2. Check if the input year meets the leap year criteria using the above-mentioned rules.
  3. If the year satisfies the criteria, it is a leap year; otherwise, it is not.

Example 1:

R




# Function to check for a leap year
is_leap_year <- function(year) {
  if ((year %% 4 == 0 && year %% 100 != 0) || year %% 400 == 0) {
    return(TRUE)
  } else {
    return(FALSE)
  }
}
 
# Input year
input_year <- 2024
 
# Check if it's a leap year
if (is_leap_year(input_year)) {
  print(paste(input_year, "is a leap year."))
} else {
  print(paste(input_year, "is not a leap year."))
}


Output:

[1] "2024 is a leap year."

Example 2:

R




# Function to check for a leap year
is_leap_year <- function(year) {
  if ((year %% 4 == 0 && year %% 100 != 0) || year %% 400 == 0) {
    return(TRUE)
  } else {
    return(FALSE)
  }
}
 
# Input year
input_year <- 1900
 
# Check if it's a leap year
if (is_leap_year(input_year)) {
  print(paste(input_year, "is a leap year."))
} else {
  print(paste(input_year, "is not a leap year."))
}


Output:

[1] "1900 is not a leap year."

Example 3:

R




# Function to check for a leap year
is_leap_year <- function(year) {
  if ((year %% 4 == 0 && year %% 100 != 0) || year %% 400 == 0) {
    return(TRUE)
  } else {
    return(FALSE)
  }
}
 
# Input year
input_year <- 1992
 
# Check if it's a leap year
if (is_leap_year(input_year)) {
  print(paste(input_year, "is a leap year."))
} else {
  print(paste(input_year, "is not a leap year."))
}


Output:

[1] "1992 is a leap year."


Contact Us