Table of Contents [hide]
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
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.
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:
Output
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.
Output
That’s all about how to increment for loop by 2 in Java.