LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Introduction to Writing Functions in R

Kurs anzeigen

Anleitung zur Übung

  • 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.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

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
  ___
}
Code bearbeiten und ausführen