The FizzBuzz Function
Part of the Fundamentals section of Coddy's R journey — lesson 53 of 78.
Challenge
EasyIn 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"ifnis divisible by both 3 and 5"Fizz"ifnis divisible by 3 only"Buzz"ifnis 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:
15The output should be:
[1] "FizzBuzz"If the input is:
9The output should be:
[1] "Fizz"If the input is:
10The output should be:
[1] "Buzz"If the input is:
7The 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
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values