freeCodeCamp Challenge Guide: Count Backwards With a For Loop

freeCodeCamp Challenge Guide: Count Backwards With a For Loop
0

Count Backwards With a For Loop

Hints

Hint 1

• create a new for loop for myArray

Hint 2

• start from the first odd number just before 9

Solutions

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

for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}

// Setup
var myArray = [];

// Only change code below this line.
for (var i = 9; i > 0; i -= 2) {
myArray.push(i);
}
``````

Just a grammatical correction, there is no such word as â€śbackwardsâ€ť, it should be â€śbackwardâ€ť.

1 Like

Since itâ€™s a wiki entry, you ought to be able to make that change yourself. Give it a try. Click on the faded ellipses at the bottom, which should expand a toolbar. Then, click on the pencil icon to edit the post.

1 Like

I suppose I could, but I was referring to the actual challenge at https://www.freecodecamp.com/challenges/count-backwards-with-a-for-loop

Even better! You can put up an issue on their GitHub page.

1 Like

// Example
var ourArray = [];

for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}

// Setup
var myArray = [];

// Only change code below this line.
for (var i=9; i > 0; i-=2) {
myArray.push(i);
}

u can use this

3 Likes

it work too!

// Setup
var myArray = [];

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

2 Likes

Something Iâ€™m not quite understanding with this one.

For the condition part in the middle of the for loop >= works, but > does not.
My understanding was that the condition is checked, and if returned True, then the final-expression is applied.
If thatâ€™s the case, shouldnâ€™t (var i = 9; i > 1; i -= 2) work?

i.e. the final check before the condition becomes False would be on the number 3, which is greater than 1, so then 2 would be subtracted from 3. This leaves us with 1, which is not greater than 1, and the loop would end.

Using >= would surely cause the final-statement to be applied one more time to i as 1, leaving us with -1, no?

For comparison, the code that doesnâ€™t pass:

// Setup
var myArray = [];

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

The code that does pass:

// Setup
var myArray = [];

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

Thanks

1 Like

Hi campers,my take:

// Example
var ourArray = [];

for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}

// Setup
var myArray = [];

// Only change code below this line.
for(var i = 9;i > 0;i -= 2) {
myArray.push(i);
}

Using a bit of logic with an if statement:

var myArray = [];

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

2 Likes