The syntax of for loop in Java is:
for(initialization; condition; iteration)
As shown above, the initialization
portion initializes the loop control variable. The condition
expression that tests the loop control variable. The iteration
is used to increment or decrement the loop control variable.
All three initialization
are optional. i.e.
we can have
loop without initialization section or condition section or iteration section.
- intialization section is called only once before the for
for starts. i.e. No matter how many iterations are there, it is executed only once at the beginning of the
for loop. That is why any declarations and intializations, which we do only once goes in this section.
- condition is checked every time before starting the iteration, and only if it is true the body is executed, else the
for loop is terminated.
- iteration is called at the end of the body after every iteration. So if there are 5 iterations, the iteration section is executed 5 times.
Here is a short program that shows how
For Loop example
public static void main(String arg)
for(int x = 0; x < 5; x++)
System.out.println("x = " + x);
System.out.println("After for loop");
x = 0
x = 1
x = 2
x = 3
x = 4
After for loop
In this example
x is the loop control variable. It is initialized to zero in the initialization portion of the
for. The condition
x < 5 is mentioned in condition portion. The iteration
x++ which is same as
x = x + 1 is mentioned in increment portion.
x is initialized to zero and then it checks for the condition
0 < 3 which is
true so, it prints x = 0, then it increments the
x value by one. Now
1 and the condition
1 < 5 is still
true, so it prints x = 1 and increments
2. The condition
2 < 5 is again checked and since it is
true, it prints x = 2.
This continues until
5. Then the condition
5 < 5 is
false, so it terminates the loop and prints After for loop.
THINGS TO TRY
- Try to print even numbers between
10 using a
- Try to print odd numbers between
20 using a