The while loop is a construct that repeatedly executes a block of code as long as a boolean condition remains true. The logical expression in while loop is evaluated first. If the logical expression evaluates to false, the body of while loop will not execute even once. If the logical expression in while evaluates to true, the statements in the body of while loop are executed. After executing the body, control jumps again at the top to recheck whether the boolean expression is still true or not. The body of the loop will continue to execute until the expression evaluates to false. When the logical expression becomes false, control continues the execution with the statements following while loop.
Syntax:
while ( expression)
{
statement(s);
}
/* Print Sequence No from 10 to 1 using while loop */
class SequenceWhile
{
public static void main(String args[] )
{
int i;
i=10;
while(i>=1)
{
System.out.print(i +”,”);
i–;
}
}
}
As we can see in above program, the value of variable i is initially set to 10. In while loop, the logical expression i >=1 evaluates to true (because 10 >1), the body of the loop will execute and 10 will be displayed on the screen. Then the value of variable I is decremented by 1 making it 9. Again, the control goes to the top and checks whether the expression i >=1 is still true or not. Since 9 >1, the expression evaluates to true, control will again execute the body of loop displaying value 9 on the screen. Again, the value of i is decremented by 1 making it 8. Again the control goes to the top to check whether the logical expression i>=1 is still true or not. Hence, the body of 100 will continue to execute for the time value of variable i is >= 1.
/* Print even numbers from 20 to 40 using while loop */
class EvenNumberWhile
{
public static void main(String args[] )
{
int i;
i=20;
while(i<=40)
{
System.out.println(i);
i+=2;
}
}
}