How do you solve FizzBuzz?

JavaScript

FizzBuzz Problem Solving:

The FizzBuzz problem is a classic programming problem often used in interviews to assess basic programming skills. The problem typically goes like this:

Q. Write a program that prints the numbers from 1 to n, but for multiples of 3, print "Fizz" instead of the number, and for multiples of 5, print "Buzz". For numbers which are multiples of both 3 and 5, print "FizzBuzz".

Solution to the FizzBuzz problem:

js Copy Code
function fizzBuzz(n) {
    for (let i = 1; i <= n; i++) {
        // Check if the number is divisible by both 3 and 5
        if (i % 3 === 0 && i % 5 === 0) {
            console.log("FizzBuzz");
        } 
        // Check if the number is divisible by 3
        else if (i % 3 === 0) {
            console.log("Fizz");
        }
        // Check if the number is divisible by 5
        else if (i % 5 === 0) {
            console.log("Buzz");
        }
        // If the number is not divisible by either 3 or 5, print the number itself
        else {
            console.log(i);
        }
    }
}

// Example usage:
fizzBuzz(15);
Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Explanation:

1. We iterate from 1 to n using a for loop.

2. We use conditional statements (if-else) to check if the current number is divisible by 3, 5, both 3 and 5, or neither.

3. Depending on the conditions, we print "Fizz", "Buzz", "FizzBuzz", or the number itself.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.