Increment for Loop by 2 in Java

In this post, we will see how to increment for loop by 2 in Java.

There are several looping statements available in Java and one of them is for loop in java.

There are three parts of for loop.

  • Initialization
  • Condition
  • Increment or decrement
for (initialization; condition; increment/decrement) {
     //block of statements
}

Initialization: Initialization statement executes at start of loop only one time.
condition:Condition gets evaluated in each iteration. For loop executes block of statements in loop unless condition returns false.
Increment/Decrement: These statements get executed in each iteration.

How to increment for loop by 2 in Java

To Increment for loop by 2 in Java, we are interested in Increment/Decrement part of for loop.

We need to use i+=2 in case we need to increment for loop by 2 in java.

for (int i = 1; i < 10; i+=2) {
    System.out.print(" "+i); // Prints 1 3 5 7 9
}

Let's say we want print all even numbers between 1 to 20 in Java.

We can write a for loop and start the loop from 2 by using i=2 in initialization part and increment the loop by 2 in each iteration by using i+=2.

Here is the program:

package org.arpit.java2blog;

public class PrintEvenNumbers {

    public static void main(String[] args) {
        for (int i=2 ;  i <=20 ; i+=2)
        {
            System.out.print(" "+i);
        }
    }
}

Output

 2 4 6 8 10 12 14 16 18 20

How to increment for loop by n in Java

We can use similar logic in case you want to increment for loop by n i.e. 2,3,4,5. We need to put i+=n in increment/decrement part of the for loop.

Here is simple program where we will increment for loop by 3.

package org.arpit.java2blog;

public class IncrementForLoopBy3 {

    public static void main(String[] args) {
        for (int i=1 ;  i <=20 ; i+=3)
        {
            System.out.print(" "+i);
        }
    }
}

Output

 1 4 7 10 13 16 19

That's all about how to increment for loop by 2 in Java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.