Unknown model· unknown
from NVIDIA HelpSteer3 Preference
Write a complete C++ implementation for FizzBuzz.
- User
Write a complete C++ implementation for FizzBuzz.
- Assistant
Certainly! Below is a complete C++ implementation for the FizzBuzz problem. The FizzBuzz problem is a classic programming problem where you print the numbers from 1 to a given number, but for multiples of three, you print "Fizz" instead of the number, and for the multiples of five, you print "Buzz". For numbers which are multiples of both three and five, you print "FizzBuzz".
Here's the implementation:
cpp#include <iostream> void fizzBuzz(int n) { for (int i = 1; i <= n; ++i) { if (i % 15 == 0) { std::cout << "FizzBuzz"; } else if (i % 3 == 0) { std::cout << "Fizz"; } else if (i % 5 == 0) { std::cout << "Buzz"; } else { std::cout << i; } std::cout << std::endl; } } int main() { int n; std::cout << "Enter a number: "; std::cin >> n; fizzBuzz(n); return 0; }Explanation:
- Include the iostream library: This is necessary for input and output operations.
- Define the
fizzBuzzfunction: This function takes an integernas a parameter and prints the FizzBuzz sequence up ton.- It uses a
forloop to iterate from 1 ton. - For each number, it checks if the number is divisible by 15 (
i % 15 == 0). If so, it prints "FizzBuzz". - If the number is not divisible by 15 but is divisible by 3 (
i % 3 == 0), it prints "Fizz". - If the number is not divisible by 3 but is divisible by 5 (
i % 5 == 0), it prints "Buzz". - If the number is not divisible by 3 or 5, it prints the number itself.
- After each print operation, it prints a newline character (
std::endl).
- It uses a
- Define the
mainfunction: This is the entry point of the program.- It prompts the user to enter a number.
- It reads the number from the user input.
- It calls the
fizzBuzzfunction with the entered number.
How to Run:
- Copy the code into a file named .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.