The Modular Operator
๐ Problem Statement
Write a program that prints the numbers from 1 to 100. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz". For numbers which are multiples of both 3 and 5, print "FizzBuzz".
๐ก Intuition
This problem tests your understanding of the modular operator () and control flow. The key insight is that you need to handle the most specific condition (divisible by both 3 AND 5) correctly. Instead of checking divisibility by 15 first, you can build the output string incrementally โ append "Fizz" if , then append "Buzz" if . This naturally produces "FizzBuzz" for multiples of both.
๐ง Approach
- Loop through numbers 1 to 100.
- For each number, initialize an empty string.
- If , append "Fizz" to the string.
- If , append "Buzz" to the string.
- If the string is still empty (not divisible by 3 or 5), print the number itself.
- Otherwise, print the constructed string.
โก Complexity Analysis
where is the range of numbers (100 in this case)
โ only a single output string variable is used
โ ๏ธ Common Mistakes
- Checking divisibility by 3 before checking for both 3 and 5, which causes "FizzBuzz" cases to print only "Fizz"
- Using
elifinstead of separateifstatements when building the string incrementally - Forgetting that is true, so starting from 0 instead of 1 gives an extra empty output
๐ฏ Final Thoughts
FizzBuzz is a classic interview warm-up that tests basic control flow and the modular operator. The string-building approach is more elegant than checking for 15 first, and it scales better if more conditions are added (e.g., "Jazz" for multiples of 7).