Menu
Coddy logo textTech

Looping The Numbers

Part of the Fundamentals section of Coddy's Swift journey — lesson 60 of 86.

challenge icon

Challenge

Easy

In the previous lesson, you created the fizzBuzz function that returns the correct string for a single number. Now, add a loop to process all numbers from 1 to a given limit.

Modify your code to:

  1. Read an integer from input representing the upper limit
  2. Use a for-in loop to iterate from 1 through the limit (inclusive)
  3. For each number, call your fizzBuzz function and print the result

You will receive the following input:

  • A single integer representing the upper limit

For example, if the input is 5, the output should be:

1
2
Fizz
4
Buzz

If the input is 15, the output should be:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Try it yourself

func fizzBuzz(_ number: Int) -> String {
    if number % 3 == 0 && number % 5 == 0 {
        return "FizzBuzz"
    } else if number % 3 == 0 {
        return "Fizz"
    } else if number % 5 == 0 {
        return "Buzz"
    } else {
        return String(number)
    }
}

// Read input
let number = Int(readLine()!)!

// Call the function and print the result
print(fizzBuzz(number))

All lessons in Fundamentals