JuniorCodeCommonNot answered yet
FizzBuzz variant: Foo for /2, Bar for /3, Buzz for /6
For every integer from 1 to n, print a label built by appending: Foo if it is divisible by 2, Bar if divisible by 3, Buzz if divisible by 6. If none apply, print the number itself.
Requirements:
- Append cumulatively, so 6 (divisible by all three) prints
FooBarBuzz. - Clarify this rule with the interviewer before coding.
void fizzbuzz(int n) {
// your code here
}
Write the implementation.
Loop i from 1 to n, build an empty string, append Foo when i % 2 == 0, Bar when i % 3 == 0, Buzz when i % 6 == 0. If the string is still empty print i, otherwise print the string. Because the rules append, a multiple of 6 yields FooBarBuzz.
- ✗Using else-if so a value gets only one label instead of appending all that apply
- ✗Not clarifying whether a multiple of 6 prints FooBarBuzz or only Buzz
- ✗Forgetting to print the number when no rule matched
- →How would you rewrite it without an explicit loop, using a functional map?
- →Why is the
% 6rule redundant if% 2and% 3already append?
Contents
Task
For numbers 1 to n, print a cumulative label (Foo/Bar/Buzz) or the number itself.
Solution
#include <string>
#include <iostream>
void fizzbuzz(int n) {
for (int i = 1; i <= n; ++i) {
std::string res;
if (i % 2 == 0) res += "Foo";
if (i % 3 == 0) res += "Bar";
if (i % 6 == 0) res += "Buzz"; // divisible by all three → FooBarBuzz
if (res.empty()) res = std::to_string(i);
std::cout << res << '\n';
}
}
Key points
- Labels append, they are not mutually exclusive — 6 yields
FooBarBuzz. - The number prints only when the string stayed empty.
- The real interview signal is the candidate clarifying the multiple-of-6 rule.
Contents