FizzBuzz and more…
Day 17/100. Been working on algorithms the last few days but it’s mainly been reading the documentation. It feels like one day I take everything in, the next its all gone. I guess that means I need to keep working harder.
First of all, I worked on the good ol’ FizzBuzz algorithm — an interviewer’s favorite. I’ve had to do it a couple of times in interviews so know this one pretty well so will just go through it for this post.
Write a program that console logs the numbers from 1 to n. But for multiples of three print “fizz” instead of the number and for the multiple of five print “buzz”. For numbers which are multiples of both three and five print “fizzbuzz”.
First of all, we want to iterate through all of the numbers up to n. From there, we need to print to the console the different numbers required. So, first of all, let's do a for loop. Remember it starts from 1, not 0, like a lot of for loops that we work on:
for(let i = 1; i <= n; i++) {};Now let's add in some logic. We’ll start off with the ‘fizzbuzz’ section. We want to do this first to that all of the numbers that are divisible by 3 & 5 show fizzbuzz. We’re going to use the remainder operator to find out if iis divisble by 3 or 5. The remainder operator divides a number by another and gives the remainder that would be left, so 5 % 3 would give a remainder of 1. In our case, we want to find a number that has no remainder. So let’s add in:
if(i % 3 == 0 && i % 5 == 0) {
console.log('fizzbuzz')
}From there, we want to find the other numbers divisible by 3 and add them to the console as ‘fizz’. For that, we will do the same but, by adding an else to the if statement.
} else if(i % 3 == 0) {
console.log('fizz')
}Then we’ll do the same again for the numbers divisible by 5.
} else if (i % 5 == 0) {
console.log('buzz')
}And don’t forget to add the other numbers to the console.
} else {
console.log((i);
}So, the final result looks like this:
function fizzBuzz(n) {
for(let i = 0; i <= n; i++) {
if(i % 3 ==0 && i % 5 == 0) {
console.log('fizzbuzz')
} else if (i % 3 == 0) {
console.log('fizz')
} else if (i % 5 == 0) {
console.log('buzz')
} else {
console.log(i)
}
}
}I do like this challenge. Even though I’ve done it a few times, I still make mistakes, usually with the logic, so it’s good to go back and revisit it sometimes.
Anyway, one to the next one.
