Menu
Topics Index
...
`

For Loop example - Java Example Program


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");
    
    }
}
OUTPUT

x = 0
x = 1
x = 2
x = 3
x = 4
After for loop

DESCRIPTION

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.
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
  • Place the code shown below in the above program and check the output
    for (int x = 5; x > 0; x--) {
        System.out.println("x = " + x);
    }
    System.out.println("After for loop");
    The output for the above code should be :
    x = 5
    x = 4
    x = 3
    x = 2
    x = 1
    After for loop

    The above shown is a decrement for loop. Initially the i value is assigned to 5 and on every iteration it is decremented by 1
  • 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.

© meritcampus 2019

All Rights Reserved.

Open In App