FizzBuzz Program in C++
This program prints numbers from 1 to 100, replacing multiples of 3 with “Fizz”, multiples of 5 with “Buzz”, and multiples of both with “FizzBuzz”.
Program Explanation
The program follows these steps:
- Loop through numbers from 1 to 100 using a
for
loop. - For each number, check if it is a multiple of both 3 and 5 by using the modulo operator
%
. If true, print “FizzBuzz”. - If the number is not a multiple of both, check if it is a multiple of 3. If true, print “Fizz”.
- If the number is not a multiple of 3, check if it is a multiple of 5. If true, print “Buzz”.
- If the number is neither a multiple of 3 nor 5, print the number itself.
C++ Program Code
// FizzBuzz program in C++
#include <iostream>
int main() {
// Loop through numbers from 1 to 100
for (int i = 1; i <= 100; ++i) {
// Check if the number is a multiple of both 3 and 5
if (i % 3 == 0 && i % 5 == 0) {
std::cout << "FizzBuzz" << std::endl;
}
// Check if the number is a multiple of 3
else if (i % 3 == 0) {
std::cout << "Fizz" << std::endl;
}
// Check if the number is a multiple of 5
else if (i % 5 == 0) {
std::cout << "Buzz" << std::endl;
}
// If none of the above, print the number itself
else {
std::cout << i << std::endl;
}
}
return 0;
}
Explanation of the C++ Code
#include <iostream>
: This is the preprocessor directive that includes the input-output stream library.int main()
: This is the main function where the program execution begins.for (int i = 1; i <= 100; ++i)
: This is the for loop that iterates from 1 to 100.if (i % 3 == 0 && i % 5 == 0)
: This condition checks if the current number is a multiple of both 3 and 5.std::cout << "FizzBuzz" << std::endl;
: If the number is a multiple of both 3 and 5, print “FizzBuzz”.else if (i % 3 == 0)
: This condition checks if the current number is a multiple of 3.std::cout << "Fizz" << std::endl;
: If the number is a multiple of 3, print “Fizz”.else if (i % 5 == 0)
: This condition checks if the current number is a multiple of 5.std::cout << "Buzz" << std::endl;
: If the number is a multiple of 5, print “Buzz”.else
: This handles the case where the number is neither a multiple of 3 nor 5.std::cout << i << std::endl;
: Print the number itself.return 0;
: Return 0 indicates that the program ended successfully.