Menu
Topics Index
...
`

While Demo - Java Example Program


While Demo
class WhileDemo
{
    public static void main(String arg[])
    {
        int x = 1;
        while( x <= 5 ) // LINE A
        {
            System.out.println("x = "+ x);
            x++;
        }
    
    }
}
OUTPUT

x = 1
x = 2
x = 3
x = 4
x = 5

DESCRIPTION

Here x is initialized to 1. In the while condition in LINE A, it checks for the condition 1 <= 5, since it is true it goes into the block and prints x = 1. Then it increments the x value by one. With x value as 2 and again it checks for the condition 2 <= 5 and prints the output as x = 2. This repeats for 3 more times, then x will become 6. Since the condition 6 <= 5 becomes false, the control comes out of while loop.

THINGS TO TRY
  • Change the above program such that the below shown output is printed.
    x = 5
    x = 4
    x = 3
    x = 2
    x = 1
  • Try to print the even numbers between 20 and 30 using a while loop.
  • Try to print the numbers which are divisible by 5 between 10 to 50.

© meritcampus 2019

All Rights Reserved.

Open In App