Menu
Coddy logo textTech

The FizzBuzz Function

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 64 of 93.

challenge icon

Challenge

Medium

In the previous lesson, you implemented the traditional FizzBuzz by printing results directly in a loop. Now, refactor your code by extracting the FizzBuzz logic into a reusable function.

Create a function called fizzBuzz that takes a single number and returns the appropriate string result.

Function requirements:

  • Name: fizzBuzz
  • Parameter: n (Int) - the number to evaluate
  • Returns: A String with the result

Return logic:

  • Return "FizzBuzz" if n is divisible by both 3 and 5
  • Return "Fizz" if n is divisible by 3 only
  • Return "Buzz" if n is divisible by 5 only
  • Return the number as a string otherwise (use n.toString())

Then, update your main function to use a loop from 1 to 15 that calls fizzBuzz for each number and prints the returned result.

Try it yourself

fun main() {
    // TODO: Write your code below
    // Implement FizzBuzz for numbers 1 to 15
    // - Print "FizzBuzz" if divisible by both 3 and 5
    // - Print "Fizz" if divisible by 3 only
    // - Print "Buzz" if divisible by 5 only
    // - Print the number itself otherwise
    
    for (i in 1..15) {
        if (i % 3 == 0 && i % 5 == 0) {
            println("FizzBuzz")
        } else if (i % 3 == 0) {
            println("Fizz")
        } else if (i % 5 == 0) {
            println("Buzz")
        } else {
            println(i)
        }
    }
}

All lessons in Fundamentals

Practice on your own: Kotlin playground