To increment the loop variable by 3 in a for
loop in Java, you can use the +=
operator to add 3 to the loop variable on each iteration.
Here's an example of how to do it:
public class Main { public static void main(String[] args) { // Count from 1 to 10 by 3s for (int i = 1; i <= 10; i += 3) { System.out.println(i); } } }
This code creates a for
loop that starts at 1, continues until it reaches 10, and increments the loop variable i
by 3 on each iteration. The loop variable i
is initialized to 1 before the loop starts, and the loop condition i <= 10
is checked before each iteration. If the condition is true, the loop continues; if the condition is false, the loop ends.
The for
loop is a useful tool for performing a set of actions a specific number of times, or for iterating over the items in an array or other collection. You can use the +=
operator or any other assignment operator to modify the loop variable in any way you like.