📜  c++ fizzbuzz - C++ (1)

📅  最后修改于: 2023-12-03 14:59:44.894000             🧑  作者: Mango

C++ FizzBuzz

Introduction

FizzBuzz is a famous coding interview question that tests a programmer's ability to write clean and efficient code. It requires the programmer to write a program that prints the numbers from 1 to 100, with some specific rules:

  • If a number is divisible by 3, print "Fizz" instead of the number.
  • If a number is divisible by 5, print "Buzz" instead of the number.
  • If a number is divisible by both 3 and 5, print "FizzBuzz" instead of the number.

In this article, we will implement the FizzBuzz problem in C++.

Code

Here's the C++ code for the FizzBuzz problem:

#include <iostream>

int main() {
  for (int i = 1; i <= 100; 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;
    }
  }
  return 0;
}

Let's go through this code step-by-step:

  • The main() function starts with a for loop that goes from 1 to 100. We use the loop variable i to represent the current number being printed.
  • We use the % (modulus) operator to check if i is divisible by 3, 5, or both. If i is divisible by both 3 and 5, we print "FizzBuzz". If i is only divisible by 3, we print "Fizz". If i is only divisible by 5, we print "Buzz". Otherwise, we print the number itself.
  • Finally, we return 0 to indicate that the program ran successfully.
Conclusion

The FizzBuzz problem is a simple but effective way to test a programmer's ability to write clean and efficient code. In this article, we implemented the FizzBuzz problem in C++ and explained the code step-by-step. I hope this was helpful to you!