Algorithms and Data Structures Part IV
Well this is a fun one and probably the most popular problem and if you’re here before reading parts I — III you can start here.
So for this problem you’re asked to write a program that console logs 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”.
example: fizzbuzz(5) outputs 1 2 fizz 4 buzz.
Okay let's get started…
So for this problem we need to determine a multiple of a given number, for this we need to use a specific operator(+, -, x, etc…) the modulo operator(%). so for example 9 % 3 will return 0 because 3 goes into 9 exactly 3 times, and so 10 % 3 will return 1 because 3 goes into ten 3 times with 1 left over, and then 11 % 3 returns 2 because theres 2 left over 12 % 3 is then 0 again as 3 goes into 12 an exact number of times. So this will determine if a number is a multiple of another. We can use for example 12 % 3 === 0 this would return true so there for we know that 12 is a multiple of 3. Now we have a way to find our multiples of 3 and 5 wu hu!
we start with our function. N will be the number we are testing…
now we need to iterate from 1 to n inside our function, lets setup a for loop to do this.
here we iterate from 1 to less than or equal to n and each time we increment by 1. It’s important to note that we start from 1, not 0 like a lot of other for loops as per the directions.
Now we can write our if statement to see if our number is a multiple of 3 AND 5…
so the first part is checking to see if we have a multiple of 3 (i % 3 === 0) and the next part checks if we have a multiple of 5 (i % 5 === 0). If we have a multiple of both then we want to console log “fizzbuzz” but only if the number is a multiple of both.
Now that we have our if statement we want to make sure the rest are else if statements, the rest may be obvious now cause all we have to do is split up the first statement into individual else if statements like so.
This is saying if the number is a multiple of 3 then log fizz but if the number is a multiple of 5, log buzz.
Then the final piece to the puzzle will say if we don’t have a multiple of 3 or 5 or 3 and 5 then log the number.
so for the TLDR of it all …
This is our “fizbuzz” solution. now you can just say something like console.log(fizzBuzz(15)) outside of the function and we would log…
1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz.
That’s all folks!
Thanks for reading!