DEV Community

NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on • Updated on

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.

Top comments (0)