Returning early
Sometimes, you don't need to run through the whole body of a function to get the answer. In that case you can return early from that function using return().
To check if x is divisible by n, you can use is_divisible_by(x, n) from assertive.
Alternatively, use the modulo operator, %%. x %% n gives the remainder when dividing x by n, so x %% n == 0 determines whether x is divisible by n. Try 1:10 %% 3 == 0 in the console.
To solve this exercise, you need to know that a leap year is every 400th year (like the year 2000) or every 4th year that isn't a century (like 1904 but not 1900 or 1905).
assertive is loaded.
Este ejercicio forma parte del curso
Introduction to Writing Functions in R
Instrucciones del ejercicio
- Complete the definition of
is_leap_year(), checking for the cases ofyearbeing divisible by 400, then 100, then 4, returning early from the function in each case.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
is_leap_year <- function(year) {
# If year is div. by 400 return TRUE
if(___) {
return(___)
}
# If year is div. by 100 return FALSE
if(___) {
___
}
# If year is div. by 4 return TRUE
___
# Otherwise return FALSE
___
}