Skip to content

Fizz Buzz c++/cpp

Fizz Buzz Problem

Fizz Buzz: Count from 1 to 100, if the number can be divided by 3, return fizz; if the number can be divided by 5, return buzz; if the number can be divided by both 3 and 5, return fizz buzz; otherwise return the number.

Program Running Output:

1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizz-buzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizz-buzz 31 32 fizz 34 buzz fizz 37 38 fizz buzz 41 fizz 43 44 fizz-buzz 46 47 fizz 49 buzz fizz 52 53 fizz buzz 56 fizz 58 59 fizz-buzz 61 62 fizz 64 buzz fizz 67 68 fizz buzz 71 fizz 73 74 fizz-buzz 76 77 fizz 79 buzz fizz 82 83 fizz buzz 86 fizz 88 89 fizz-buzz 91 92 fizz 94 buzz fizz 97 98 fizz buzz

Fizz Buzz Problem in c++ :

c++ Raw Loop and if Implementation

Loop from 1 to 100, check each number, first judge if it's multiples 15, then 3, then 5, using if else-if else.

fizz.cpp
// Fizz Buzz c++/cpp
#include <iostream>

int main()
{
        for (int i=1; i<=100; i++)
        {
                if (i%15==0)
                        std::cout << "fizz-buzz ";
                else if (i%3==0)
                        std::cout << "fizz ";
                else if (i%5==0)
                        std::cout << "buzz ";
                else
                        std::cout << i << ' ';
        }
        std::cout << std::endl;
}
jamroot (b2 jamfile; applied to all c++ code below.)

jamroot

exe fizz : fizz.cpp : : <cxxstd>20 ;

c++ array: std::array Implementation

std::array is one of STL containers.

Store the result into std::array.

Note that the loop begins from 1, but the container index begins from 0.

// Fizz Buzz c++/cpp
#include <iostream>
#include <array>
#include <string>

int main()
{
        std::array<std::string, 100> array;
        for (int i=1; i<=100; i++)
                if (i%15==0)
                        array[i-1] = "fizz-buzz";
                else if (i%3==0)
                        array[i-1] = "fizz";
                else if (i%5==0)
                        array[i-1] = "buzz";
                else
                        array[i-1] = std::to_string(i);
        for (auto & value: array)
                std::cout << value << ' ';
        std::cout << std::endl;
}

 

 

 

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Form options

Submitted comments will be subject to moderation before being displayed.

@cppfx.xyz