Menu
Coddy logo textTech

The FizzBuzz Function

Part of the Fundamentals section of Coddy's R journey — lesson 53 of 78.

challenge icon

Challenge

Easy

In the previous lesson, you created a check_divisible function. Now, build the core fizzbuzz function that determines what to output for a single number.

Create a function called fizzbuzz that takes one argument: n. The function should return:

  • "FizzBuzz" if n is divisible by both 3 and 5
  • "Fizz" if n is divisible by 3 only
  • "Buzz" if n is divisible by 5 only
  • The number itself (as a character string) if none of the above apply

Use as.character() to convert the number to a string when returning the number itself.

Read a number from input, convert it to a numeric value, and call your fizzbuzz function. Print the returned result.

For example, if the input is:

15

The output should be:

[1] "FizzBuzz"

If the input is:

9

The output should be:

[1] "Fizz"

If the input is:

10

The output should be:

[1] "Buzz"

If the input is:

7

The output should be:

[1] "7"

Try it yourself

# Read input
con <- file("stdin", "r")
number <- as.numeric(suppressWarnings(readLines(con, n = 1)))
divisor <- as.numeric(suppressWarnings(readLines(con, n = 1)))

# TODO: Create a function called check_divisible that takes two arguments:
# number and divisor. Return TRUE if number is divisible by divisor, FALSE otherwise.
check_divisible <- function(number, divisor) {
  return(number %% divisor == 0)
}

# Call your function and print the result
print(check_divisible(number, divisor))

All lessons in Fundamentals