FizzBuzz using JavaScript Switch [duplicate] - javascript

This question already has answers here:
javascript fizzbuzz switch statement
(8 answers)
Closed 4 years ago.
Can't seem to point out something obvious. This solution doesn't work. Please help?
FizzBuzz question: Print numbers from 1 to 100. Print Fizz instead of numbers divisible by 3. Print Buzz instead of numbers divisible by 5. Print FizzBuzz instead of numbers divisible by both 3 and 5.
for(var i = 1; i <= 100; i++) {
switch (i) {
case (i%3 === 0 && i%5 === 0):
console.log('FizzBuzz');
break;
case (i%3 === 0):
console.log('Fizz');
break;
case (i%5 === 0):
console.log('Buzz');
break;
default:
console.log(i);
}
}

The problem is, you are switching on the value of variable i. Then you are comparing that with expressions like i % 3 === 0, so the comparison becomes i === (i % 3 === 0).
Instead, you can switch on true, so any expression evaluating to true will be switched into.
for (var i = 1; i <= 100; i++) {
switch (true) {
case (i % 3 === 0 && i % 5 === 0):
console.log('FizzBuzz');
break;
case (i % 3 === 0):
console.log('Fizz');
break;
case (i % 5 === 0):
console.log('Buzz');
break;
default:
console.log(i);
}
}

A switch enters the branch if the case matches the value you are switching for, therefore:
switch (i) {
case (i%3 === 0 && i%5 === 0):
Will enter the first case if:
i === (i%3 === 0 && i%5 === 0)
E.g. for 15 it will be:
15 === true // -> false
so it wont enter the branch. Therefore instead of switching for i you have to switch for true:
switch(true) {

Did you try not to break the switch, because when it matches it won't print the other stuff it is supposed to? Maybe?

Related

can I use the 'switch' statement in any of the questions below? or is the 'else if' the right way to go?

I am trying to write a function that satisfies the following:
-count from 1 to 100,
-on numbers divisible with 4 print “byfour”,
-on numbers divisible with 6 print “bysix”,
-on numbers divisible with both 4 and 6 print “byfoursix”,
-skip numbers divisible with 7,
-on the number 32 add '!'.
This is what I have, but I was wondering if there is way to use the switch statement, or any more optimal way to write it.
function maths(){
for (let i=1; i<=100; i++){
if (i === 32){
console.log (`${i}!`);
}
else if (i % 4 === 0 && i % 6 === 0){
console.log ("byfoursix");
}
else if (i % 4 ===0) {
console.log ("byfour");
}
else if (i % 6 === 0) {
console.log ("bysix");
}
else if (i % 7 === 0){
continue;
}
else {
console.log (i);
}
}
}
maths();
Any input or advice is super appreciated! Thank you
It is possible to use a switch case if you wanted to by setting the switch parameter to true so that it runs, although it's not necessarily a better way to write it.
for (let i = 1; i <= 100; i++) {
switch (true) {
case (i === 32):
console.log(`${i}!`);
break;
case (i % 4 === 0 && i % 6 === 0):
console.log('byfoursix');
break;
case (i % 4 === 0):
console.log('byfour');
break;
case (i % 6 === 0):
console.log('bysix');
break;
case (i % 7 === 0):
break;
default:
console.log(i);
}
}

JS - Appending a logged sequence of numbers

I've made a sequence of numbers from 0 to 20 and I want to change the sequence so once it comes up with a multiple of 3 and 5 it logs 'FizzBuzz' to the terminal then carries on with the rest of the numbers up to 20. My problem is once I have changed the number to the string the rest of the terms in the sequence come up with NaN. I know the problem with my code is that I'm changing the number to a string and you cannot perform addition to a string which is why NaN comes up. I'm pretty new to this so any thoughts on how to do complete this would be greatly appreciated. I've tried using .append() but I'm pretty sure I'm using it incorrectly.
My code thus far;
var increment = function(number)
{
for (var i = 1; i <= 20; i++)
{
console.log(number++)
if ((number % 3 === 0) && (number % 5 === 0))
{
number = "FizzBuzz"
console.log("FizzBuzz");
}
else if (number % 3 === 0)
{
console.log("Fizz");
}
else if (number % 5 === 0)
{
console.log("Buzz");
}
else
{}
}
}
increment(1)
When you find a multiple of 3 and 5, you are setting number to "FizzBuzz", which does not have a ++ operator. On the next iteration, you call ++ on number, which is now "FizzBuzz", so it logs NaN.
If you don't set number to "FizzBuzz" it should work fine.
This would do it
var increment = function()
{
for (var i = 1; i <= 20; 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)
}
}
}
increment()
There's no need to pass the number parameter, since your for loop is already set to increment by 1 (i++).

similar to FizzBuzz with a twist

Write a javascript program that displays the numbers from 10 to 100. But for multiples of 4 print "Penny" instead of the number and for multiples of 6 print "Leonard". For numbers which are multiples of both 4 and 6 print "Bazzinga"
I know how to do two parts struggling to print 6 and 4;
function baZzinga (number) {
for (var number = 10; number <= 101; number++)
if(number % 4 == 0) {
console.log("penny");
}
else if (number % 6 == 0) {
console.log("Leonard");
} else if ( not sure what goes here) {
help help help
} else {
console.log(number");
}
You want the and condition first. Try this
var result = document.getElementById("result");
function baZzinga (number) {
for (var number = 10; number <= 101; number++) {
if (number % 4 == 0 && number % 6 == 0) {
result.innerHTML += "Bazinga";
}
else if(number % 4 == 0) {
result.innerHTML += "penny";
}
else if (number % 6 == 0) {
result.innerHTML += "Leonard";
}
else {
result.innerHTML += number;
}
}
}
baZzinga()
<p id="result"></p>
I changed console.log to result.innerHTML because I wanted to demonstrate it in a snippet.
I have a few comments on your code -- constructive criticism, I hope! First, you don't need the number parameter in your bazzinga function. Next, the indentation of the code you posted makes it hard to read. Finally, you should almost always use === instead of ==. The === tests for strict equality, whereas == tries to do some type conversions first (and can therefore produce unexpected results). See the official docs.
To answer you question: check for divisibility by 6 AND 8 first. That way, it will override the individual cases. I believe you want something like this:
function bazzinga() {
for (var number = 10; number <= 100; number++) {
if (number % 4 === 0 && number % 6 === 0) {
console.log("Bazzinga");
} else if (number % 4 === 0) {
console.log("Penny");
} else if (number % 6 === 0) {
console.log("Leonard");
}
}
}
Here is a solution using the format you posted:
for (var number = 10; number <= 100; number++) {
if(number % 4 === 0 && number % 6 === 0){
console.log("bazzinga");
} else if(number % 4 === 0) {
console.log("penny");
} else if (number % 6 === 0) {
console.log("Leonard");
} else {
console.log(number);
}
}
Or use the ternary operator to be even more succinct!
for (var i = 10; i <= 100; i++){
var penny = i % 4 === 0;
var leonard = i % 6 === 0;
console.log(penny ? (leonard ? "bazzinga" : "penny"): leonard ? "leonard" : i);
}
function process_num(num) {
return num % 4 == 0 ? num % 6 == 0 ? "Bazzinga" : "Penny" : num % 6 == 0 ? "Leonard" : num;
}
for (x = 10; x <= 100; x++) { console.log( x + ': is ', process_num(x)) }
Nested Ternary operator for conciseness
If it passes outer ternary test it is divisible by 4:
Enter into nested termary one to test if num is also divisible by 6 for the BaZzinga prize!!
If it fails the BaZzinga challenge, we know it previously passed the divisible by 4 test so print "penny"
Failing the outer ternary condition, we know it's not divisible by 4:
Enter nested ternary two to consider if divisible by 6. If so print "Leonard".
If not it's failed both the outer (div by 4) and inner (div by 6) so return the number unchanged.
Now that the logic is contained in the function, we can just create a for loop to iterate over the required numbers printing out the correct values.

Why doesn't my if / else statement work properly?

I am trying to iterate through the arrays in the numbers variable, and if a number can be divided by 3 I'm logging "fizz", if it can be divided by 5 I'm logging "buzz", and if a number can be divided by 3 + 5, or 15, I'm logging "fizzbuzz"
Here is the working code:
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {
if (i % 15 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}
};
Here is my original code, which doesn't log "fizzbuzz"
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {
if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 15 === 0) {
console.log("FizzBuzz");
} else {
console.log(i);
}
};
Why does the (i % 15 === 0) condition need to precede the other two conditions? Shouldn't it not matter?
The number 15 is divisible by both 3 and 5. If you don't test it first, then you'll never get there.
So let's take 30 as an example. If you check 15 first, you'll see that it's divisible by 15. However, if you check either 5 or 3 first, it'll be flagged as being divisible by either of those.
After one of your conditions evaluates as true, you break out of that if-block and don't evaluate following else-if/else statements. If you want the rest of them to evaluate you can make them if statements instead of else-if's.
It's because firstly the computer checks for the first statement and then the others as you use the ELSE IF which means, to check the statement after the first one is false. Use IF for all instead.

What is wrong with this very simple switch statement? [duplicate]

This question already has answers here:
Expression inside switch case statement
(8 answers)
Closed 8 years ago.
The evaluations in the console print in the second line seem correct, but the switch statement won't work. And I am not getting any errors.
for (var i = 0; i < 100; i++) {
console.log(i % 3 === 0, i % 5 === 0);
switch (i) {
case i % 3 === 0:
console.log(i, " by three");
break;
case i % 5 === 0:
console.log(i, " by five ");
break;
}
}
http://jsfiddle.net/vL4omdxs/
As the comment said, that's not how you use switch/case.
You evaluate the condition in switch, then create different behaviours using cases.
Here is your code slightly modified (actually not so slightly, there's a small math twist):
var res = document.getElementById('r');
for (var i = 0; i < 100; i++) {
//console.log(i % 3 === 0, i % 5 === 0);
switch (i % 15) {
case 0:
r.innerHTML += i + " by three and five<br>";
break;
case 3:
case 6:
case 9:
case 12:
r.innerHTML += i + " by three<br>";
break;
case 5:
case 10:
r.innerHTML += i + " by five<br>";
break;
}
}
<div id="r"></div>
Just a hint (offtopic, but might help): switch/case is not the best approach for the 3/5 problem. See how much simpler it looks using ifs:
var res = document.getElementById('r');
for (var i = 0; i < 100; i++) {
res.innerHTML += "<br>" + i + ": ";
if (i % 3 == 0) {
res.innerHTML += "by three ";
}
if (i % 5 == 0) {
res.innerHTML += "by five ";
}
}
<div id="r"></div>
Case expressions are tested for strict equality so you need to change the switch from switch (1) to switch (true). However note that only one of the case blocks will be executed.
That's not the way to do the switch statement. It must be:
switch (i % 3) {
case 0:
...
break;
case 1:
...
break;
}
The expression within switch brackets is compared with the expression after case keyword. Take your code as example:
for (var i = 0; i < 100; i++) {
console.log(i % 3 === 0, i % 5 === 0);
switch (i) {
case i % 3 === 0: // if (i) equals (i % 3 === 0), run this branch
console.log(i, " by three");
break;
case i % 5 === 0: // if (i) equals (i % 5 === 0), run this branch
console.log(i, " by five ");
break;
}
}
And please remember, "equal" here means ===. Since your case expressions all return boolean, they'll never be equal to your i, which is a number.

Categories