Page 244 - IT-802_class_12
P. 244
{
System.out.print (“Square of “ + number);
System.out.println (“ = “ + number*number);
++number;
}
while (number <= 5);
}}
The output of the DoWhileDemo program is the same as WhileDemo program. You might be wondering if both the
while and do-while loops give the same output, what is the use of having two types of loop constructs. Well, consider
the case when the variable number is initialized to 6.
int number = 6;
The while loop would first test whether number <= 5. Since 6 > 5, the condition is false and the loop body would not be
entered and as a result nothing is displayed in the output window. However, in the case of the do-while loop, since the
body of the loop is executed before the test condition, the square of 6 is printed (“Square of 6 = 36”), then, number is
incremented to 7. Now the test for number >= 5 is made. Since 7 > 5, the condition is false and the loop is exited. To
summarize, the do-while loop always executes at least once whereas the while loop executes zero or more times. The
differences between while and do-while loop are as follows:
Difference between while and do-while loop
While Loop Do While Loop
A while loop is an entry-controlled loop – it tests for A do-while loop is an exit-controlled loop it tests
a condition prior to running a block of code. for a condition after running a block of code.
A while loop runs zero or more times. Body of loop A do-while loop runs once or more times but at
may never be executed. least once.
The variables in the test condition must be initialized Body of loop is executed at least once It is not
prior to entering the loop structure. necessary to initialize the variables in the test
While condition prior to entering the loop structure.
(condition) do
{ {
Statements statements
} }
while (condition);
242 Touchpad Information Technology-XII

