freeCodeCamp Challenge Guide: Iterate Odd Numbers With a For Loop

Iterate Odd Numbers With a For Loop


Hints

Hint 1

After string // Only change code below this line. we add for loop. You need to copy loop from the top:

for (var i = 0; i < 10; i += 2) {
  ourArray.push(i);
}

Hint 2

And change initialization var i = 0 to var i = 1, also you need change name of the array ourArray to myArray:

for (var i = 1; i < 10; i += 2) {
  myArray.push(i);
}

Solutions

Solution 1 (Click to Show/Hide)
var ourArray = [];

for (var i = 0; i < 10; i += 2) {
  ourArray.push(i);
}

// Setup
var myArray = [];

// Only change code below this line.

for (var i = 1; i < 10; i += 2) {
  myArray.push(i);
}

Solution
to go from counting even number to odd numbers change the count variable initialization from 0 to 1 and the < to <= to include 9 in the array.

for (var count = 1; count <= 9; count +=2){
myArray.push(count);
}

2 Likes

I tried to find the remainder to determine if it was a odd number, and if it was a odd number the code pushes it to the array.

var myArray = [];

for (var i = 0; i < 10; i++) {
if(i%2 == 1){
myArray.push(i);
}
}

2 Likes

Simple code to get exact answer!
var myArray = [];

// Only change code below this line.
for(i=1;i < 10; i+=2){
myArray.push(i);
}
console.log(myArray);

Another option with bit change in code
for(i=1;i <= 9; i+=2)

1 Like

This is how I did it:

// Example
var ourArray = [];

for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}

// Setup
var myArray = [];

// Only change code below this line.
for(var i = 1;i <= 9;i += 2) {
myArray.push(i);
}

1 Like

Using an if statement.

// Setup
var myArray = [];

// Only change code below this line.
for(var i = 0; i < 10; i++){
if(i % 2 !== 0){
myArray.push(i);
}
}

1 Like

// Example
var ourArray = [];

for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}

//It’s my solution
// Setup
var myArray = [];
for (var i = 0; i <= 9; i++){
if(i%2){
myArray.push(i);
}
}
// Only change code below this line.