DEV Community

NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on • Edited on

4 2

Algorithm 101: 2 Ways to FizzBuzz a Range of Numbers

In the last article, we looked at how we can fizzBuzz a signle number. This article is taking us further to how we can fizzBuzz a range of number. It is going to however, depend upon the function from the last article - 4 Ways to FizzBuzz a Single Number.

fizzBuzzRange([1, 9]) 
/* 
  1
  2
  Fizz
  4
  Buzz
  Fizz
  7
  8
  Fizz
*/
fizzBuzzRange([30, 25])
/*
  FizzBuzz
  29
  28
  Fizz
  26
  Buzz
*/
Enter fullscreen mode Exit fullscreen mode

Are you already thinking it out? I will be showing you 2 ways to do this both for a descending range (example: from 9 to 1) and ascending range (example: from 1 to 9)

Prerequisite

To benefit from this article, you need to check out the preceding article and possess basic understanding of javascript's array methods.

Let's FizzBuzz a Range of Numbers Using:

  • if...statement and for...loop
      function fizzBuzzRange(array) {
        if (array[0] < array[1]) {
          for (let i = array[0]; i <= array[1]; i++) {
            console.log(fizzBuzz(i));
          }
        }

        if (array[0] > array[1]) {
          for (let i = array[0]; i >= array[1]; i--) {
            console.log(fizzBuzz(i));
          }
        }
      }
Enter fullscreen mode Exit fullscreen mode
  • switch...statement and while...loop
      function fizzBuzzRange(array) {
        switch (array[0] < array[1]) {
          case true:
            counter = array[0];
            while (counter <= array[1]) {
              console.log(fizzBuzz(counter));
              counter++;
            }
            break;

          case false:
            counter = array[0];
            while (counter >= array[1]) {
              console.log(fizzBuzz(counter));
              counter--;
            }
            break;
        }
      }
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are many ways to solve problems programmatically. I will love to know other ways you solved yours in the comment section.

Up Next: Algorithm 101: 3 Ways to Get the Fibonacci Sequence

If you have questions, comments or suggestions, please drop them in the comment section.

You can also follow and message me on social media platforms.

Twitter | LinkedIn | Github

Thank You For Your Time.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay