Menu
Coddy logo textTech

Looping The Numbers

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

challenge icon

Challenge

Medium

In the previous lesson, you created the fizzBuzz function that returns the appropriate string for a single number. Now, make your program dynamic by reading the upper limit from input instead of hardcoding 15.

Modify your code to:

  1. Read an integer n from input (the upper limit)
  2. Loop from 1 to n (inclusive)
  3. For each number, call your fizzBuzz function and print the result

Keep your existing fizzBuzz function unchanged - it should still return:

  • "FizzBuzz" if divisible by both 3 and 5
  • "Fizz" if divisible by 3 only
  • "Buzz" if divisible by 5 only
  • The number as a string otherwise

Input: A single integer representing the upper limit

Output: The FizzBuzz result for each number from 1 to n, each on its own line

Try it yourself

fun fizzBuzz(n: Int): String {
    return if (n % 3 == 0 && n % 5 == 0) {
        "FizzBuzz"
    } else if (n % 3 == 0) {
        "Fizz"
    } else if (n % 5 == 0) {
        "Buzz"
    } else {
        n.toString()
    }
}

fun main() {
    for (i in 1..15) {
        println(fizzBuzz(i))
    }
}

All lessons in Fundamentals

Practice on your own: Kotlin playground