The syntax of for loop in Java is:
for(initialization; condition; iteration)
{
// body
}
As shown above, the
initialization portion initializes the loop control variable. The
condition is a
boolean
expression that tests the loop control variable. The
iteration is used to increment or decrement the loop control variable.
All three
initialization,
condition and
iteration are optional.
i.e. we can have
for
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 works:
For Loop example
class ForExample
{
public static void main(String arg[])
{
for(int x = 0; x < 5; x++)
{
System.out.println("x = " + x);
}
System.out.println("After for loop");
}
}
OUTPUTx = 0
x = 1
x = 2
x = 3
x = 4
After for loop
DESCRIPTIONIn 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.
First 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 x
is 1
and the condition 1 < 5
is still true
, so it prints x = 1 and increments x
to 2
. The condition 2 < 5
is again checked and since it is true
, it prints x = 2.
This continues until x
becomes 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
0
to 10
using a for
loop.
- Try to print odd numbers between
11
to 20
using a for
loop.