Page 243 - IT-802_class_12
P. 243
Note the use of the ++ operator to increment the value of number. The statement ++number or number++; has the
same effect as the statement number = number + 1;
More About Loop
1. Indent your loops, begin the statements in the body of the loop with a tab/ spaces inside the curly braces. This will
make the code easier to read, understand and debug. The NetBeans IDE automatically provides code indentation.
Indented Code Non Indented Code
int number = 1; int number = 0;
while (number >=10) while (number >=0)
{ {
System.out.println(nu mber); number = number System.out.println(numb er); number = number
+ 1; + 1;
} }
2. If there is only one statement in the body of the loop, the set of curly braces enclosing the body can be omitted.
For example,
while ( number < another_number)
++number;
3.4.7 The Do While Statement
The do while statement evaluates the test after executing the body of a loop. The syntax of the Java do while statement
is as shown:
do
{
Statements
}
while (expression);
Let us write the same program to print the squares of numbers from 1 to 5. This time we will use a do-while loop. The
following steps need to be performed.
1. Initialize number = 1
2. Print the square of the number
3. Increment number (number = number + 1)
4. Test if the number <= 5
5. If yes, Go back to step 2 If no, Exit the loop The tasks that need to be performed repeatedly are in steps 2 and
3 – these constitute the body of the loop.
The test condition is in step 4. The corresponding Java code is as below:
public class DoWhileDemo
{
public static void main (String[ ] args)
{
int number = 1;
do
Fundamentals of Java Programming 241

