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
1 2 3 4 5 |
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.
1 2 3 4 5 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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
1 2 3 |
2 4 6 8 10 12 14 16 18 20 |
Further reading:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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 2 3 |
1 4 7 10 13 16 19 |
That’s all about how to increment for loop by 2 in Java.