Learn C++ · lesson 21 of 61 · about 9 minutes
Project: FizzBuzz
A troll guards the bridge with a counting game: check the number the hero picks, then count with Fizz for 3s and Buzz for 5s.
What you'll learn
- Combine loops and conditions
- Order checks correctly
- Build output with std::string
The troll's game
A troll blocks the bridge and will only let the hero cross after a counting game. The hero picks how far to count, from 1 to 30, and the troll checks every number: Fizz for a multiple of 3, Buzz for a multiple of 5, FizzBuzz for both. It's the classic interview puzzle, FizzBuzz.
The rules
For each number from 1 to n:
- divisible by 3 and 5: FizzBuzz
- divisible by 3: Fizz
- divisible by 5: Buzz
- otherwise the number
A neat trick: build the word from pieces, and print the number only if the word is still empty.
FizzBuzz by building a string
#include <iostream>
#include <string>
int main() {
for (int i = 1; i <= 15; i++) {
std::string word;
if (i % 3 == 0) word += "Fizz";
if (i % 5 == 0) word += "Buzz";
std::cout << (word.empty() ? std::to_string(i) : word) << " ";
}
std::cout << "\n";
}Output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzzThe troll checks the number first
#include <iostream>
#include <string>
int main() {
int count = 5;
if (count < 1 || count > 30) {
std::cout << "The troll only counts from 1 to 30.\n";
} else {
for (int n = 1; n <= count; n++) {
std::string word;
if (n % 3 == 0) {
word += "Fizz";
}
if (n % 5 == 0) {
word += "Buzz";
}
std::cout << (word.empty() ? std::to_string(n) : word) << "\n";
}
std::cout << "The troll lets you cross.\n";
}
}Output
1
2
Fizz
4
Buzz
The troll lets you cross.Tip
The building approach needs no special FizzBuzz case: 15 collects both pieces by itself. Adding a new rule, like 7 for Bazz, is one more line.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.