Menu
Topics Index
...
`

Do While Demo - Java Example Program


Do While Demo
class DoWhileDemo
{
    public static void main(String arg[])
    {
        int x = 1;
        do
        {
            System.out.println("The x value is: " + x);
            x++;
        } while( x <= 3 ); // LINE A
    }
}
OUTPUT

The x value is: 1
The x value is: 2
The x value is: 3

DESCRIPTION

Here the x is initialized to 1. Now the control enters the do block and prints the x value as The x value is: 1 then, it increments the x value by 1. So x becomes 2. Then it checks for the condition 2 <= 3 which is true, so it prints The x value is: 2 and repeats the same. Next it prints The x value is: 3, then x value will become 4 so the condition 4 <= 3 will become false causing the loop to terminate.

THINGS TO TRY
  • Remove the semicolon at LINE A. It should give a compilation Error.
  • Print the numbers which are divisible by 3 between 3 to 30.
  • Print the numbers which are divisible by 2 between 40 to 60.

© meritcampus 2019

All Rights Reserved.

Open In App