FizzBuzz
FizzBuzz combines a loop, divisibility tests, and ordered conditions.
What is FizzBuzz?
FizzBuzz combines a loop, divisibility tests, and ordered conditions.
Print Fizz, Buzz, or FizzBuzz for numbers from 1 through 15.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
for (int n = 1; n <= 15; ++n) {
// Check the most specific condition first.
if (n % 15 == 0) puts("FizzBuzz");
else if (n % 3 == 0) puts("Fizz");
else if (n % 5 == 0) puts("Buzz");
else printf("%d\n", n);
}
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
C++
main.cpp
#include <iostream>
int main() {
for (int n = 1; n <= 15; ++n) {
// Check the most specific condition first.
if (n % 15 == 0) std::cout << "FizzBuzz\n";
else if (n % 3 == 0) std::cout << "Fizz\n";
else if (n % 5 == 0) std::cout << "Buzz\n";
else std::cout << n << '\n';
}
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
C and C++ comparison
Test divisibility by both 3 and 5 first so multiples of 15 are not handled by an earlier branch.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.