Phil Powis
Phil Powis

Reputation: 173

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 :)

Upvotes: 3

Views: 218

Answers (1)

Or Neeman
Or Neeman

Reputation: 1216

The problem is you were checking the divisibility of i (which starts at 0) rather than of numberArray[i] (which starts at 1).

Upvotes: 4

Related Questions