Looping Through Numbers
Part of the Fundamentals section of Coddy's R journey — lesson 54 of 78.
Challenge
EasyIn the previous lesson, you created the fizzbuzz function that handles a single number. Now, add a loop to process a range of numbers from 1 to a given limit.
Modify your code to:
- Read a number
nfrom input (this will be the upper limit) - Use a for loop to iterate from 1 to
n - For each number in the range, call your
fizzbuzzfunction and print the result
Each result should be printed on a new line using print().
For example, if the input is:
5The output should be:
[1] "1"
[1] "2"
[1] "Fizz"
[1] "4"
[1] "Buzz"If the input is:
15The output should be:
[1] "1"
[1] "2"
[1] "Fizz"
[1] "4"
[1] "Buzz"
[1] "Fizz"
[1] "7"
[1] "8"
[1] "Fizz"
[1] "Buzz"
[1] "11"
[1] "Fizz"
[1] "13"
[1] "14"
[1] "FizzBuzz"Try it yourself
# Read input
con <- file("stdin", "r")
number <- as.numeric(suppressWarnings(readLines(con, n = 1)))
# Function from previous lesson
check_divisible <- function(number, divisor) {
return(number %% divisor == 0)
}
# Create the fizzbuzz function
fizzbuzz <- function(n) {
if (check_divisible(n, 3) && check_divisible(n, 5)) {
return("FizzBuzz")
} else if (check_divisible(n, 3)) {
return("Fizz")
} else if (check_divisible(n, 5)) {
return("Buzz")
} else {
return(as.character(n))
}
}
# Call the fizzbuzz function and print the result
print(fizzbuzz(number))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