Fizz Buzz - CPP Solution

1. Introduction

In this blog post, we'll tackle a classic programming challenge known as "Fizz Buzz". This problem is often used in coding interviews to assess basic programming skills, particularly in control flow and conditional logic. It's a simple yet illustrative example of iteration and string manipulation in C++.

Problem

The task is to implement a function that takes an integer n and returns a string array answer (1-indexed). For each integer i from 1 to n, the array should contain:

- "FizzBuzz" if i is divisible by both 3 and 5.

- "Fizz" if i is divisible by 3 only.

- "Buzz" if i is divisible by 5 only.

- The string representation of i if none of the above conditions are met.

2. Solution Steps

1. Create a vector of strings to store the results.

2. Iterate from 1 to n.

3. For each number, check if it is divisible by 3, 5, or both:

- Append "FizzBuzz" to the vector if the number is divisible by both 3 and 5.

- Append "Fizz" if it is divisible by 3 only.

- Append "Buzz" if it is divisible by 5 only.

- Otherwise, append the number as a string.

4. Return the resulting vector.

3. Code Program

#include <iostream>
#include <vector>
#include <string>
using namespace std;

// Function to perform the Fizz Buzz logic
vector<string> fizzBuzz(int n) {
    vector<string> result;
    for (int i = 1; i <= n; i++) {
        if (i % 3 == 0 && i % 5 == 0) {
            // Divisible by both 3 and 5
            result.push_back("FizzBuzz");
        } else if (i % 3 == 0) {
            // Divisible by 3 only
            result.push_back("Fizz");
        } else if (i % 5 == 0) {
            // Divisible by 5 only
            result.push_back("Buzz");
        } else {
            // Neither, so add the number itself
            result.push_back(to_string(i));
        }
    }
    return result;
}

int main() {
    int n = 15;
    vector<string> output = fizzBuzz(n);

    cout << "Fizz Buzz up to " << n << ":" << endl;
    for (const string &s : output) {
        cout << s << endl;
    }
    return 0;
}

Output:

Fizz Buzz up to 15:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Explanation:

1. The function takes the integer 15 and iterates from 1 to 15.

2. For each number, it checks divisibility by 3 and 5 and appends the appropriate string to the result vector.

3. Numbers like 3 and 6 result in "Fizz", 5 and 10 in "Buzz", 15 in "FizzBuzz", and others in their string representations.

4. The output is a sequence that correctly follows the Fizz Buzz logic, showcasing fundamental conditional checks and iteration in C++.


Comments