Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a for loop increment/decrement by more than one?

People also ask

Can you increment 2 variables in a for loop?

Incrementing two variables is bug prone, especially if you only test for one of them. For loops are meant for cases where your loop runs on one increasing/decreasing variable. For any other variable, change it in the loop.

Can increment be more than 1?

In programming, however, when you increment a variable it implies 1 unless there is a specific other amount. (Cf. the "increment" operator in C-syntax languages. The ++ always means +=1 and the decrement operator ( -- ) always means -=1 .)

Is ++ and ++ i in for loop the same?

Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated. To answer the actual question, however, they're essentially identical within the context of typical for loop usage.

Can we use decrement in for loop?

For decrementing the For loop, we use the step value as a negative integer. In the above example, the starting point is set as a higher limit and the endpoint as a lower limit, and a negative step value for decrementing for the loop. We can also decrement a While loop.


Use the += assignment operator:

for (var i = 0; i < myVar.length; i += 3) {

Technically, you can place any expression you'd like in the final expression of the for loop, but it is typically used to update the counter variable.

For more information about each step of the for loop, check out the MDN article.


A for loop:

for(INIT; TEST; ADVANCE) {
    BODY
}

Means the following:

INIT;
while (true) {
    if (!TEST)
        break;
    BODY;
    ADVANCE;
}

You can write almost any expression for INIT, TEST, ADVANCE, and BODY.

Do note that the ++ operators and variants are operators with side-effects (one should try to avoid them if you are not using them like i+=1 and the like):

  • ++i means i+=1; return i
  • i++ means oldI=i; i+=1; return oldI

Example:

> i=0
> [i++, i, ++i, i, i--, i, --i, i]
[0, 1, 2, 2, 2, 1, 0, 0]

for (var i = 0; i < 10; i = i + 2) {
    // code here
}​

Andrew Whitaker's answer is true, but you can use any expression for any part.
Just remember the second (middle) expression should evaluate so it can be compared to a boolean true or false.

When I use a for loop, I think of it as

for (var i = 0; i < 10; ++i) {
    /* expression */
}

as being

var i = 0;
while( i < 10 ) {
    /* expression */
    ++i;
}