The
while
statement continually executes a block of statements while a particular condition is true.
Its syntax can be expressed as:
while (expression) {
statement;
}
The
while
statement evaluates
expression, which must return a
boolean
value. If the
expression is
true
, then the
while
loop executes the statement in the
while
block. The
while
loop continues testing the expression and executing its block until the controlling expression evaluates to
false
.
while
loop can be used to print the values from 1 through 5. It is shown in the following WhileDemo 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++;
}
}
}
OUTPUTx = 1
x = 2
x = 3
x = 4
x = 5
DESCRIPTIONHere 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
.
The major differences between
for
and
while
are:
for
loop is used when we know the number of iterations we have to perform i.e. we know how many times we need to execute a loop.
while
is used when you are not sure about the iterations but you know what the condition is and then you can loop that block until the condition is false
.
- Although
for
and while
are different, every for
loop can be rewritten using while
and every while
can be rewritten using for
.