how to make a for loop increment by 2 in java

www.l‮.iruttua‬com
how to make a for loop increment by 2 in java

To make a for loop increment by 2 in Java, you can specify the increment value as 2 in the loop's increment statement.

Here is an example of a for loop that increments by 2:

for (int i = 0; i < 10; i += 2) {
    // code to be executed
}

In this example, the loop will iterate five times, with the value of i starting at 0 and incrementing by 2 on each iteration. The loop will terminate when i is greater than or equal to 10.

You can also use a for loop to increment by any other value by specifying the desired increment value in the loop's increment statement. For example, to increment by 3, you can use the following loop:

for (int i = 0; i < 15; i += 3) {
    // code to be executed
}

This loop will iterate five times, with the value of i starting at 0 and incrementing by 3 on each iteration. The loop will terminate when i is greater than or equal to 15.

Keep in mind that the increment value can be negative, in which case the loop will decrement on each iteration. For example, to decrement by 2, you can use the following loop:

for (int i = 10; i > 0; i -= 2) {
    // code to be executed
}

This loop will iterate five times, with the value of i starting at 10 and decrementing by 2 on each iteration. The loop will terminate when i is less than or equal to 0.

Created Time:2017-11-01 20:42:57  Author:lautturi