How to resolve the algorithm FizzBuzz step by step in the C++ programming language

Published on 7 June 2024 03:52 AM

How to resolve the algorithm FizzBuzz step by step in the C++ programming language

Table of Contents

Problem Statement

Write a program that prints the integers from   1   to   100   (inclusive).

But:

The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm FizzBuzz step by step in the C++ programming language

Source Code 1

This code is a simple implementation of the FizzBuzz problem in C++ using standard input/output streams. It iterates through numbers from 1 to 4,000,000,000 and checks if each number is divisible by 3 or 5. If it is divisible by 3, it increments the fizz counter. If it is divisible by 5, it increments the buzz counter. If it is divisible by both 3 and 5, it increments the fizzbuzz counter. The code prints the counts of each type of number at the end.

Source Code 2

This code is a simple implementation of the FizzBuzz problem in C++ using a loop. It iterates through numbers from 1 to 100 and prints "Fizz" if the number is divisible by 3, "Buzz" if the number is divisible by 5, "FizzBuzz" if the number is divisible by both 3 and 5, and the number itself otherwise.

Source Code 3

This code is a simple implementation of the FizzBuzz problem in C++ using conditional statements. It iterates through numbers from 0 to 100 and prints "Fizz" if the number is divisible by 3, "Buzz" if the number is divisible by 5, "FizzBuzz" if the number is divisible by both 3 and 5, and the number itself otherwise.

Source Code 4

This code is a simple implementation of the FizzBuzz problem in C++ using a loop and a switch statement. It iterates through numbers from 1 to 100 and prints "Fizz" if the number is divisible by 3, "Buzz" if the number is divisible by 5, "FizzBuzz" if the number is divisible by both 3 and 5, and the number itself otherwise.

Source Code 5

This code is a simple implementation of the FizzBuzz problem in C++ using a range-based for loop and a lambda expression. It iterates through numbers from 1 to 100 and prints "Fizz" if the number is divisible by 3, "Buzz" if the number is divisible by 5, "FizzBuzz" if the number is divisible by both 3 and 5, and the number itself otherwise.

Source Code 6

This code is a meta-programming implementation of the FizzBuzz problem in C++ using template metaprogramming. It defines a template class fizzbuzz that evaluates to different strings depending on the value of its template parameters n, m3, and m5. The fb_run class then instantiates the fizzbuzz class with n set to 100, which evaluates to the string "FizzBuzz" for multiples of 15, "Fizz" for multiples of 3, "Buzz" for multiples of 5, and the number itself otherwise.

Source Code 7

This code is a meta-programming implementation of the FizzBuzz problem in C++ using Boost MPL. It defines several template meta-functions to perform calculations on numbers and strings. The IntToStr template meta-function converts an unsigned integer to a character array. The FizzBuzz template meta-function uses the other template meta-functions to generate a string that contains the FizzBuzz sequence for the given number N. The main function then instantiates the FizzBuzz template meta-function with N set to 7 and prints the resulting string.

Each of these code snippets is a different implementation of the FizzBuzz problem in C++, demonstrating different programming techniques and meta-programming approaches.

Source code in the cpp programming language

#include <iostream>
#include <chrono>

int main()
{

	int fizz = 0, buzz = 0, fizzbuzz = 0;

	bool isFizz = false;

	auto startTime = std::chrono::high_resolution_clock::now();

	for (unsigned int i = 1; i <= 4000000000; i++) {
		isFizz = false;

		if (i % 3 == 0) {
			isFizz = true;
			fizz++;
		}

		if (i % 5 == 0) {
			if (isFizz) {
				fizz--;
				fizzbuzz++;
			}
			else {
				buzz++;
			}
		}

	}

	auto endTime = std::chrono::high_resolution_clock::now();
	auto totalTime = endTime - startTime;

	printf("\t fizz : %d, buzz: %d, fizzbuzz: %d, duration %lld milliseconds\n", fizz, buzz, fizzbuzz, (totalTime / std::chrono::milliseconds(1)));

	return 0;
}


#include <iostream>

using namespace std;
int main ()
{
       for (int i = 1; i <= 100; i++) 
       {
               if ((i % 15) == 0)
                       cout << "FizzBuzz\n";
               else if ((i % 3) == 0)
                       cout << "Fizz\n";
               else if ((i % 5) == 0)
                       cout << "Buzz\n";
               else
                       cout << i << "\n";
       }
       return 0;
}


#include <iostream>
using namespace std;

int main()
{
  for (int i = 0; i <= 100; ++i)
  {
    bool fizz = (i % 3) == 0;
    bool buzz = (i % 5) == 0;
    if (fizz)
      cout << "Fizz";
    if (buzz)
      cout << "Buzz";
    if (!fizz && !buzz)
      cout << i;
    cout << "\n";
  }
  return 0;
}


#include <iostream>

int main()
{
    int i, f = 2, b = 4; 

    for ( i = 1 ; i <= 100 ; ++i, --f, --b )
    {
        if ( f && b ) { std::cout << i;             }
        if ( !f )     { std::cout << "Fizz"; f = 3; }
        if ( !b )     { std::cout << "Buzz"; b = 5; }
        std::cout << std::endl;
    }

    return 0;
}


#include <iostream>                                                                                                     
#include <algorithm>
#include <vector>

int main()
{
  std::vector<int> range(100);
  std::iota(range.begin(), range.end(), 1);

  std::vector<std::string> values;
  values.resize(range.size());

  auto fizzbuzz = [](int i) -> std::string {
    if ((i%15) == 0) return "FizzBuzz";
    if ((i%5) == 0)  return "Buzz";
    if ((i%3) == 0)  return "Fizz";
    return std::to_string(i);
  };

  std::transform(range.begin(), range.end(), values.begin(), fizzbuzz);

  for (auto& str: values) std::cout << str << std::endl;

  return 0;
}


#include <iostream>

template <int n, int m3, int m5> 
struct fizzbuzz : fizzbuzz<n-1, (n-1)%3, (n-1)%5>
{
  fizzbuzz() 
  { std::cout << n << std::endl; }
};

template <int n>
struct fizzbuzz<n, 0, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5>
{
  fizzbuzz() 
  { std::cout << "FizzBuzz" << std::endl; }
};

template <int n, int p>
struct fizzbuzz<n, 0, p> : fizzbuzz<n-1, (n-1)%3, (n-1)%5>
{
  fizzbuzz() 
  { std::cout << "Fizz" << std::endl; }
};

template <int n, int p>
struct fizzbuzz<n, p, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5>
{
  fizzbuzz() 
  { std::cout << "Buzz" << std::endl; }
};

template <>
struct fizzbuzz<0,0,0>
{
  fizzbuzz() 
  { std::cout << 0 << std::endl; }
};

template <int n>
struct fb_run
{
  fizzbuzz<n, n%3, n%5> fb;
};

int main()
{
  fb_run<100> fb;
  return 0;
}


#include <iostream>
#include <string>
#include <cstdlib>
#include <boost/mpl/string.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/size_t.hpp>

using namespace std;
using namespace boost;

///////////////////////////////////////////////////////////////////////////////
// exponentiation calculations
template <int accum, int base, int exp> struct POWER_CORE : POWER_CORE<accum * base, base, exp - 1>{};

template <int accum, int base>
struct POWER_CORE<accum, base, 0>
{
    enum : int { val = accum };
};

template <int base, int exp> struct POWER : POWER_CORE<1, base, exp>{};

///////////////////////////////////////////////////////////////////////////////
// # of digit calculations
template <int depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_CORE<depth + 1, i / 10>{};

template <int depth>
struct NUM_DIGITS_CORE<depth, 0>
{
    enum : int { val = depth};
};

template <int i> struct NUM_DIGITS : NUM_DIGITS_CORE<0, i>{};

template <>
struct NUM_DIGITS<0>
{
    enum : int { val = 1 };
};

///////////////////////////////////////////////////////////////////////////////
// Convert digit to character (1 -> '1')
template <int i>
struct DIGIT_TO_CHAR
{
    enum : char{ val = i + 48 };
};

///////////////////////////////////////////////////////////////////////////////
// Find the digit at a given offset into a number of the form 0000000017
template <unsigned int i, int place> // place -> [0 .. 10]
struct DIGIT_AT
{
    enum : char{ val = (i / POWER<10, place>::val) % 10 };
};

struct NULL_CHAR
{
    enum : char{ val = '\0' };
};

///////////////////////////////////////////////////////////////////////////////
// Convert the digit at a given offset into a number of the form '0000000017' to a character
template <unsigned int i, int place> // place -> [0 .. 9]
    struct ALT_CHAR : DIGIT_TO_CHAR< DIGIT_AT<i, place>::val >{};

///////////////////////////////////////////////////////////////////////////////
// Convert the digit at a given offset into a number of the form '17' to a character

// Template description, with specialization to generate null characters for out of range offsets
template <unsigned int i, int offset, int numDigits, bool inRange>  
    struct OFFSET_CHAR_CORE_CHECKED{};
template <unsigned int i, int offset, int numDigits>                
    struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, false> : NULL_CHAR{};
template <unsigned int i, int offset, int numDigits>                
    struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, true>  : ALT_CHAR<i, (numDigits - offset) - 1 >{};

// Perform the range check and pass it on
template <unsigned int i, int offset, int numDigits>
    struct OFFSET_CHAR_CORE : OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, offset < numDigits>{};

// Calc the number of digits and pass it on
template <unsigned int i, int offset>
    struct OFFSET_CHAR : OFFSET_CHAR_CORE<i, offset, NUM_DIGITS<i>::val>{};

///////////////////////////////////////////////////////////////////////////////
// Integer to char* template. Works on unsigned ints.
template <unsigned int i>
struct IntToStr
{
    const static char str[];
    typedef typename mpl::string<
    OFFSET_CHAR<i, 0>::val,
    OFFSET_CHAR<i, 1>::val,
    OFFSET_CHAR<i, 2>::val,
    OFFSET_CHAR<i, 3>::val,
    OFFSET_CHAR<i, 4>::val,
    OFFSET_CHAR<i, 5>::val,
    /*OFFSET_CHAR<i, 6>::val,
    OFFSET_CHAR<i, 7>::val,
    OFFSET_CHAR<i, 8>::val,
    OFFSET_CHAR<i, 9>::val,*/
    NULL_CHAR::val>::type type;
};

template <unsigned int i>
const char IntToStr<i>::str[] = 
{
    OFFSET_CHAR<i, 0>::val,
    OFFSET_CHAR<i, 1>::val,
    OFFSET_CHAR<i, 2>::val,
    OFFSET_CHAR<i, 3>::val,
    OFFSET_CHAR<i, 4>::val,
    OFFSET_CHAR<i, 5>::val,
    OFFSET_CHAR<i, 6>::val,
    OFFSET_CHAR<i, 7>::val,
    OFFSET_CHAR<i, 8>::val,
    OFFSET_CHAR<i, 9>::val,
    NULL_CHAR::val
};

template <bool condition, class Then, class Else>
struct IF
{
    typedef Then RET;
};

template <class Then, class Else>
struct IF<false, Then, Else>
{
    typedef Else RET;
};


template < typename Str1, typename Str2 >
struct concat : mpl::insert_range<Str1, typename mpl::end<Str1>::type, Str2> {};
template <typename Str1, typename Str2, typename Str3 >
struct concat3 : mpl::insert_range<Str1, typename mpl::end<Str1>::type, typename concat<Str2, Str3 >::type > {};

typedef typename mpl::string<'f','i','z','z'>::type fizz;
typedef typename mpl::string<'b','u','z','z'>::type buzz;
typedef typename mpl::string<'\r', '\n'>::type mpendl;
typedef typename concat<fizz, buzz>::type fizzbuzz;

// discovered boost mpl limitation on some length

template <int N>
struct FizzBuzz
{
    typedef typename concat3<typename FizzBuzz<N - 1>::type, typename IF<N % 15 == 0, typename fizzbuzz::type, typename IF<N % 3 == 0, typename fizz::type, typename IF<N % 5 == 0, typename buzz::type, typename IntToStr<N>::type >::RET >::RET >::RET, typename mpendl::type>::type type;
};

template <>
struct FizzBuzz<1>
{
    typedef mpl::string<'1','\r','\n'>::type type;
};

int main(int argc, char** argv)
{
    const int n = 7;
    std::cout << mpl::c_str<FizzBuzz<n>::type>::value << std::endl;
	return 0;
}


  

You may also check:How to resolve the algorithm Pig the dice game step by step in the Maple programming language
You may also check:How to resolve the algorithm Fast Fourier transform step by step in the Racket programming language
You may also check:How to resolve the algorithm Remove lines from a file step by step in the Ring programming language
You may also check:How to resolve the algorithm Empty string step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Perfect numbers step by step in the Julia programming language