And The Good - for loop counting starts at i = 1?


#1

Hello magnificent people,

I noticed all of the solutions posted have the for loop starting at i = 1. My understanding is that the first position in an array is accessed by i = 0. (zero based indexing)

So to count through the numbers listed in the array (1, 2, ...., 20), wouldn't our for loop start at i = 0, and finish at i <=19?

Why are the correct solutions starting their for loops at i = 1, and not the first position, which is i = 0?

var numList = [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 < 20; i++){
    if ((i % 3 === 0) && !(i % 5 === 0)){
        console.log("Fizz");
    }
    
    else if (!(i % 3 === 0) && (i % 5 === 0)){
        console.log("Buzz");
    }
        
    else if ((i % 3 === 0) && (i % 5 === 0)){
            console.log("FizzBuzz");
    }
        
    else {
        console.log(i);
    }
};

#2

Since we are only using counting numbers, a sequence is unnecessary. The i in the loop is all we need. However, if you wish to use an array sequence, then refer to the array:

if (numList[i] % 3 === 0 && numList[i] % 5 === 0) {
    console.log("FizzBuzz");
}

and so on.


#3

Thanks you! You totally just corrected misconception I have been having about the for loop. I really appreciate it!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.