CODE
class WhileDemo
{
public static void main(String arg[])
{
int x = 1;
while( x <= 5 ) // LINE A
{
System.out.println("x = "+ x);
x++;
}
}
}
x = 1
x = 2
x = 3
x = 4
x = 5
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.
20
and 30
using a while
loop.5
between 10
to 50
.