Hunter
Hunter

Reputation: 1601

Adding if condition in special case

This is my code

for(var i = 1; i <= 20; i = i + 1)

if(i%3==0)  {
    console.log("Fizz");
}else if (i%5==0){
    console.log("Buzz");
} 
else {
    console.log(i);
}

Answer is

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz
16
17
Fizz
19
Buzz

But look at that "15"...it says "Fizz" but it should be "FizzBuzz" because it's divisible by both 3 and 5. Oops! How can i add special condition for this case

Upvotes: 0

Views: 209

Answers (5)

Paul S.
Paul S.

Reputation: 66404

I would group the if structre like so

var i = 0;
while( ++i < 21 ){
    if ( i % 3 === 0 ) {
        if ( i % 5 === 0 ) console.log('FizzBuzz'); // Special case
        else console.log('Fizz');
    }
    else if ( i % 5 === 0 ) {
        console.log('Buzz');
    }
    else console.log(i);
}

jsPerf of some of the answers given here.

Upvotes: 1

bukart
bukart

Reputation: 4906

you shouldn't write else if

for(var i = 1; i <= 20; i = i + 1)

    if(i%3==0)  {
        console.log("Fizz");
    }
    if (i%5==0){
        console.log("Buzz");
    } 
    if (i%5 && i%3) {
        console.log(i);
    }
}

Upvotes: 3

enhzflep
enhzflep

Reputation: 13109

Instead of acting instantly, take some time to further consider your inputs. If you're careful, you can avoid repeating operations like the pair of mods (%3 & %5).

var result;
for(var i = 1; i <= 20; i = i + 1)
{
    result = '';

    if(i%3==0)
        result += 'Fizz';

    if(i%5==0)
        result += 'Buzz';

    // if neither of the two preceding statements assigned a value to result
    // then it's not divisible by either - just print the number.
    if (result.length == 0)
        result = i;

    console.log(result);
}

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382514

When you do if else if, you don't pass in the else if the first condition is verified.

Here's a possible solution to your problem (there are many, none very elegant) :

var special = false;
if (i%3==0) {
    console.log("Fizz");
    special = true
}
if (i%5==0){
    console.log("Buzz");
    special = true;
} 
if (!special) {
    console.log(i);
}

Here's another one :

var tolog = '';
if (i%3==0) {
    tolog += "Fizz";
}
if (i%5==0){
    tolog += "Buzz";
} 
console.log(tolog || i);

Demonstration

Upvotes: 5

J. K.
J. K.

Reputation: 8368

If you use if-else, only one of the branches is executed. You need to have a different structure.

for (var i ... ) {
  if (i % 3 !== 0 && i % 5 !== 0) {
    console.log(i);
  } else {
    if (i % 3 === 0) { console.log('Fizz'); }
    if (i % 5 === 0) { console.log('Buzz'); }
  }
}

Upvotes: 2

Related Questions