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.
This exercise is part of the course
Introduction to Writing Functions in R
Exercise instructions
- Complete the definition of
is_leap_year()
, checking for the cases ofyear
being divisible by 400, then 100, then 4, returning early from the function in each case.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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
___
}