freeCodeCamp Challenge Guide: Count Backwards With a For Loop

freeCodeCamp Challenge Guide: Count Backwards With a For Loop
0.0 0

#1

A for loop can also count backwards, so long as we can define the right conditions.

In order to count backwards by twos, we’ll need to change our initialization, condition, and final-expression.

We’ll start at i = 10 and loop while i > 0. We’ll decrement i by 2 each loop with i -= 2.

var ourArray = [];

for(var i = 10; i > 0; i -= 2) {

  ourArray.push(i);

}

ourArray will now contain [10,8,6,4,2]


#2

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


#3

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.


#4

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


#5

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


#6

Thank you for your assistance!


#7

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


#8

it work too!

// Setup
var myArray = [];

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


#9

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


#10

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


#11

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