Java Bitwise AND and OR Exclusive OR and shift operators
To understand the necessity of a while loop consider that we wish to print a table of inch to centimeter from 1 inches to 10 inches. Here is a program that does it.
|
If you compile and run this program, you will get the output as follows
C:\Program Files\Java\jdk1.7.0_17\bin>java inchcm Inch cm 1 2.54 2 5.08 3 7.62 4 10.16 5 12.7 6 15.24 7 17.78 8 20.32 9 22.86 10 25.4 |
Here is the same thing accomplished using while loop.
|
If you compile and run this program, you will get the output as follows
C:\Program Files\Java\jdk1.7.0_17\bin>java whileexample Inch cm 1 2.54 2 5.08 3 7.62 4 10.16 5 12.7 6 15.24 7 17.78 8 20.32 9 22.86 10 25.4 |
Formally, a while construct is defined as
|
The expression is evaluated and if not found true, the list of the statements in curly brackets are executed. Typically, within the curly bracket one of variables is changed and is evaluated again in the next iteration of the while loop.
A do while loop is another similar construct in which the expression is evaluated at the end of the statements. We present here the same example with do while loop.
|
In the do-while loop the the expression is evaluated at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. The while loop and the do loop are equivalent in their expressive power. You can rewrite a while loop using a do loop, and vice versa.
Formally a do while loop is defined as
|
Special Considerations - while loop with increment decrement operators
Care should be taken to understand the number of times a while loop executes when used with increment operators. Take this example
|
How many times the statement Welcome to Java printed ?
The first time the expression
while (count++ <= 3)
is evaluated,
the count value is incremented AFTER the comparison. So the first time, the we are comparing 0 with 3. Therefore the loop is executed 4 times.
Exercises
Exercise 1
Write Java code using while loop to print a table of degree centrigrade to degree fahrenheit. The table should list degree centrigrade from 0 to 20 in steps of 2.
Exercise 2
Repeat the above code using do while
Exercise 3
How many times is the while looop executed in the following code
br />
|
Answer : 5