Reputation: 2936
Find out leap year in R
year <- 1990
if((year %% 4) == 0){
if((year %% 100) == 0){
if((year %% 400) == 0){
print(paste(year,"is a leap year"))
}
else{
print(paste(year,"is a leap year"))
}
}
else{
print(paste(year,"is not a leap year"))
}
}
The code is fine for year 2020 or 2000. But I did not get output for year 1990.
Can anyone tell me what is the problem with this code?
Upvotes: 0
Views: 59
Reputation: 389175
I think the logic was bit incorrect in your attempt. Also you needed another else
at the end for the first if
.
year <- 1990
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"))
}
You might also want to consider using leap_year
function from lubridate
which does this out of the box.
lubridate::leap_year(1990)
#[1] FALSE
lubridate::leap_year(2000)
#[1] TRUE
Particularly, the leap_year in the function is given by
(year%%4 == 0) & ((year%%100 != 0) | (year%%400 == 0))
Upvotes: 2