Write a complete C++ implementation for FizzBuzz.
- User
Write a complete C++ implementation for FizzBuzz.
Assistant
Below is a complete, well-documented C++ implementation for the classic FizzBuzz problem. The FizzBuzz problem is a simple programming task often used in software development interviews to assess basic coding skills. Here's how it typically goes:
FizzBuzz Problem Statement:
- Print numbers from 1 to
N(whereNis provided by the user or predefined). - For multiples of 3, print "Fizz" instead of the number.
- For multiples of 5, print "Buzz" instead of the number.
- For numbers which are multiples of both 3 and 5, print "FizzBuzz".
C++ Implementation:
cpp#include <iostream> /** * @brief Prints FizzBuzz sequence up to the given number. * * @param n The upper limit of the FizzBuzz sequence. */ void printFizzBuzz(int n) { for (int i = 1; i <= n; ++i) { if (i % 3 == 0 && i % 5 == 0) { std::cout << "FizzBuzz" << std::endl; } else if (i % 3 == 0) { std::cout << "Fizz" << std::endl; } else if (i % 5 == 0) { std::cout << "Buzz" << std::endl; } else { std::cout << i << std::endl; } } } /** * @brief Main function to get user input and initiate FizzBuzz print. * * @return int Exit status. */ int main() { int n; // Prompt user for the upper limit std::cout << "Enter the upper limit (N) for FizzBuzz: "; std::cin >> n; // Validate input (ensure it's a positive integer) while (n <= 0) { std::cout << "Please enter a positive integer: "; std::cin >> n; } // Print FizzBuzz sequence std::cout << "FizzBuzz Sequence up to " << n << ":" << std::endl; printFizzBuzz(n); return 0; }How to Use:
- Print numbers from 1 to
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.