freeCodeCamp Challenge Guide: Count Backwards With a For Loop

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);
}
12 Likes

Just a grammatical correction, there is no such word as “backwards”, it should be “backward”.

5 Likes

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

1 Like

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

2 Likes

Thank you for your assistance!

// 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

4 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

4 Likes

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);
}
}

4 Likes