IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Introduction to Writing Functions in R

Visualizza il corso

Istruzioni dell'esercizio

  • Complete the definition of is_leap_year(), checking for the cases of year being divisible by 400, then 100, then 4, returning early from the function in each case.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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
  ___
}
Modifica ed esegui il codice