Menu
Coddy logo textTech

Looping Through Numbers

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

challenge icon

Challenge

Easy

In 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:

  1. Read a number n from input (this will be the upper limit)
  2. Use a for loop to iterate from 1 to n
  3. For each number in the range, call your fizzbuzz function and print the result

Each result should be printed on a new line using print().

For example, if the input is:

5

The output should be:

[1] "1"
[1] "2"
[1] "Fizz"
[1] "4"
[1] "Buzz"

If the input is:

15

The 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