Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

FizzBuzz Explained

Problem Statement

Write a program that prints the numbers from 1 to n. For multiples of 3, print "Fizz" instead of the number, and for multiples of 5, print "Buzz". For numbers that are multiples of both 3 and 5, print "FizzBuzz". This classic coding challenge tests your ability to combine loops with conditional logic to produce a specific output pattern based on divisibility rules.

Example

Input: n = 15

Output:

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

Code

Java
Python
JavaScript
public class Solution {
    public void fizzBuzz(int n) {
        for (int i = 1; i <= n; i++) {
            if (i % 3 == 0 && i % 5 == 0) {
                System.out.println("FizzBuzz");
            } else if (i % 3 == 0) {
                System.out.println("Fizz");
            } else if (i % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(i);
            }
        }
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        sol.fizzBuzz(15);
    }
}
            
def fizz_buzz(n):
    for i in range(1, n + 1):
        if i % 3 == 0 and i % 5 == 0:
            print("FizzBuzz")
        elif i % 3 == 0:
            print("Fizz")
        elif i % 5 == 0:
            print("Buzz")
        else:
            print(i)

# Example usage
fizz_buzz(15)
            
function fizzBuzz(n) {
    for (let i = 1; i <= n; i++) {
        if (i % 3 === 0 && i % 5 === 0) {
            console.log("FizzBuzz");
        } else if (i % 3 === 0) {
            console.log("Fizz");
        } else if (i % 5 === 0) {
            console.log("Buzz");
        } else {
            console.log(i);
        }
    }
}

// Example usage
fizzBuzz(15);
            

Explanation

  • Iterate through numbers from 1 to n using a loop.
  • For each number, check if it is divisible by both 3 and 5 (i.e., divisible by 15). If true, print "FizzBuzz".
  • If not, check if it is divisible by 3. If true, print "Fizz".
  • If not divisible by 3, check if it is divisible by 5. If true, print "Buzz".
  • If none of the above conditions are met, print the number itself.
  • The order of checks is important: check for both 3 and 5 first to avoid printing "Fizz" or "Buzz" for numbers like 15.

Note

FizzBuzz is often used as an introductory coding problem to assess basic programming skills. Its time complexity is O(n), as it requires a single pass through the numbers from 1 to n. Ensure the modulo checks are performed efficiently to handle large values of n.