Page 242 - IT-802_class_12
P. 242
3.4.6 The While Loop
The Java while loop is used to execute a set of statements repeatedly based on a given condition. It is used when the
number of iterations is not known.
The syntax of the while loop is:
initialization;
while(test condition)
{
// body of the loop
increment or decrement;
}
Let us write a program to print the squares of numbers from 1 to 5. The following steps need to be performed.
1. Initialize number = 1
2. Test if the number <= 5
3. If yes, print the square of the number; Increment number (number = number + 1) Go back to step 2.
4. If no, exit the loop.
The tasks that need to be performed repeatedly are in step 3 – these constitute the body of the loop. The test
condition is in step 2. The corresponding Java code is given below:
5. The While Statement while (expression)
public class WhileDemo
{
public static void main (String[ ] args)
{
int number = 1;
while (number <= 5)
{
System.out.print (“Square of “ + number);
System.out.println (“ = “ + number*number);
++number;
}
}
}
240 Touchpad Information Technology-XII

