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

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.

Related

Fizz Buzz Solution: Unexpected Token Function?

I'm having some frustration with this code. I may not be seeing it.
I keep getting either an "Unexpected Token" or "ILLEGAL" error (the latter which completely preplexed me, considering I've never seen an error like that before in my life.
I've been double checking the syntax and I'm thinking it may be something I'm just not catching?
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) {
4 print ("fizz")
5 }
6 if (n%5===0) {
7 print ("buzz")
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i];
11 }
12 }
13 }
14
15
16 fizzBuzz(100);
I'd be thankful for the help! <3
You need some changes:
remove line numbers,
check first for 'fizz buzz' value and use console.log for output. Then use continue statement for jumping to top for next loop,
use i instead of n for checking.
function fizzBuzz(n) {
for (i = 0; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("fizz buzz");
continue;
}
if (i % 3 === 0) {
console.log("fizz");
continue;
}
if (i % 5 === 0) {
console.log("buzz");
continue;
}
console.log(i);
}
}
fizzBuzz(100);
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) { You're checking if the maximum number (n) is divisible by 3.
4 print ("fizz") You should be checking i.
5 }
6 if (n%5===0) { You're checking if the maximum number (n) is divisible by 5.
7 print ("buzz") You should be checking i.
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i]; You're returning an array with a single element: i.
11 } You should print i instead.
12 }
13 }
14
15
16 fizzBuzz(100);
The line numbers are what's causing the "ILLEGAL" error. Remove them.
print in JavaScript opens the print dialog to literally print paper out of a printer. Use console.log
If a number is divisible by both 3 and 5, fizzbuzz should be printed. Your code prints fizz and buzz on separate lines.
Working version ( https://www.youtube.com/watch?v=QPZ0pIK_wsc ) :
function fizzBuzz(n) {
for (var i = 0; i <= n; i++) {
var printVal = "";
if (i % 3 === 0) {
printVal += "fizz";
}
if (i % 5 === 0) {
printVal += "buzz";
}
if (printVal === "") {
printVal = i;
}
console.log(printVal);
}
}
fizzBuzz(100);
Lets decrease number of if statements, I have seen many fizzbuzzs - I would like to try another approach
const fizzBuzz = (i = 0, ret) => {
while (++i, ret = '', i <= 100) {
if (i % 3 === 0) {
ret += `fizz`
}
if (i % 5 === 0) {
ret += `buzz`
}
console.log(ret || i)
}
}
fizzBuzz()
The most important part is console.log(ret || i) - empty string is falsy value, so console will log ret if there is some value or current i value
If you're trying to print to your browser's console, use console.log() instead of print(), since print() will open the printer preview in a browser. I'm using Chrome. Remember to check the console by pressing F12 and clicking on "console" in case you've created a html file that includes your javascript script.
Since you are iterating i until it reaches the value of n, you if statements should look like:
if(i%3===0){
// your code...
}
Based on your code, it seems like you want to check for a value that is not a multiple of 3 && a multiple of 5. However, the fizzbuzz challenge requires to print fizzbuzz when encountering a number that is both a multiple of 3 && a multiple of 5. So, you'll need to add the following condition:
if (i%3 === 0 && i%5 === 0) {
console.log("fizzbuzz");
continue; /* Continue may or may not be necessary depending on your program's logic. Continue allows to re-enter the loop
without checking for the remaining if statements. If you use continue, this condition must be the first if statement inside the loop */
}
Your function doesn't need to return anything, since you're using console.log() to visualize the values in each loop iteration. That's why you need to change return [i] for console.log(i).
Don't give up and keep trying!
If you have further questions, I'll be glad to help you.

FizzBuzz only prints numbers divisible by three

I am learning JavaScript, and an exercise that I am doing...I don't seem to "get" it.
The objective to write a program using console.log that prints all numbers from 1 to 100, with exceptions.
The program should print "FizzBuzz" if the number is divisible by 3 and 5.
The program should print "Fizz" only if the number is divisible by 3.
The program should print "Buzz" only if the number is divisible by 5.
If these exceptions do not apply to the numbers from 1 to 100, the number on its own should be printed.
Here is my code:
for (i = 0; i <= 100; i++) {
if (i % 3 == 0)
if (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)
}
}
Of course, this code does not work.
The numbers that do not apply to the exceptions do not print. Numbers from 1 to 100 do not print.
Any help explaining why...I would be very thankful.
Thank you.
Your attempt doesn't work, since it only logs those values to the console that are i%3 === 0, since the first if has to be true before the second block is entered.
You can see this if you log the numbers that get printed:
for (i = 0; i <= 100; i++) {
if (i % 3 == 0) // only if this returns "true" the next block will execute
if (i % 5 == 0) {
console.log("FizzBuzz " + i)
} else if (i % 3 == 0) {
console.log("Fizz " + i)
} else if (i % 5 == 0) {
console.log("Buzz " + i)
} else {
console.log(i)
}
}
Combine the first two if statements and it works!
for (i = 0; i <= 100; 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)
}
}
You need to combine the first two if statements with && (a boolean operator that means "and". For it to become true, both of the statements must be true. If one of them is false, it becomes false).
JSFiddle (open the console to see it working): http://jsfiddle.net/7236jnx4/
You can not just have this code:
if(i%3==0)
if(i%5==0){
console.log("FizzBuzz");
}
Only numbers that are divisible by 3 will be checked by the other if statements. The first two if statements need to be combined together for it to work:
if(i%5==0&&i%3==0){
console.log("FizzBuzz");
}
for (let i = 0; i <= 100; i++) {
if (i % 5 == 0&&i%3==0) {
console.log("FizzBuzz");
} else if (i % 3 == 0) {
console.log("Fizz")
} else if (i % 5 == 0) {
console.log("Buzz")
} else {
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++).

For loop where i need to print out number from 1 to 20

So what i need to do in this task is to print out the numbers from 1-20. And the code should also fulfill the rules:
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in the
console.
Otherwise, just print out the number.
for ( var i = 0 ; i < 20 ; i++) {
if ( i % 3) {
console.log("Fizz");
}
else if( i % 5) {
console.log("Buzz");
}
else if(i % 3 || 5) {
console.log("FizzBuzz");
}
else {
console.log(i);
}
}
The error i am getting :"You printed FizzBuzz when you should have printed 1"
You have some errors in your code
for (var i = 1; i < 21; i++) { // needs to start with 1
// You should check this condition first
if (i % 3 == 0 && i % 5 == 0) { //needs '==' and '&&' operator
console.log("FizzBuzz");
} else if (i % 3 == 0) { // you need to check for equality to zero
console.log("Fizz");
} else if (i % 5 == 0) { // here too, needs '=='
console.log("Buzz");
} else {
console.log(i);
}
}
A one line solution
for(i=1;i<=20;i++)console.log((!(i%3)?'Fizz':'')+(!(i%5)?'Buzz':'') || i);
Tests for matches using two conditional (ternary) operators. The results are concatenated, eliminating the need for a third "matches both" test. A logical OR is used to print the index when the string result is empty, i.e., no matches. A single console statement outputs the final result.
As for the errors in OP's code, #elclanrs already pointed out the problem in a comment. else if(i % 3 || 5) is incorrect (suggest printing the result in the console to see why).
Run the snippet to try
// Here we output to the screen rather than the console
for(i=1;i<=20;i++)window.stdout.innerHTML+='<li>'+((!(i%3)?'Fizz':'')+(!(i%5)?'Buzz':'')||i);
<ol id="stdout">

Understanding Difference in results between two code solutions

I am newbie here in more way than one, so please go easy on me :)
Here is a problem I was tasked with solving using javascript:
Print out the numbers from 1 - 20.
The rules:
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in the console.
Otherwise, just print out the number.
Here was my first attempt at approaching it:
var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for(var i = 0; i < numberArray.length; i++){
if(i % 3 === 0 && i % 5 === 0){
console.log("FizzBuzz");
}
else if(i % 3 === 0 && i % 5 !== 0){
console.log("Fizz");
}
else if(i % 3 !== 0 && i % 5 === 0){
console.log("Buzz");
}
else {
console.log(numberArray[i]);
}
}
This returned the following incorrect values:
FizzBuzz
2
3
Fizz
5
Buzz
Fizz
8
9
Fizz
Buzz
12
Fizz
14
15
FizzBuzz
17
18
Fizz
20
I then took a different approach which DID result in the correct answer:
var fizBuzz = function() {
for (i = 1; i < 21; 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);
}
}
};
fizBuzz();
Would someone be willing to help me understand what was wrong about the first approach? This is really bothering me :)
The problem is you were checking the divisibility of i (which starts at 0) rather than of numberArray[i] (which starts at 1).

Categories