The third control structure allows us to repeat parts of a program. The first form is
Expand|Select|Wrap|Line Numbers
- while (some condition) do something
e.g. print a line of *
Expand|Select|Wrap|Line Numbers
- public class Line
- {
- public static void main(String argv[])
- {
- int i=5;
- while (i>0)
- {
- System.out.print('*');
- i--;
- }
- System.out.println();
- }
- }
e.g. A nested loop that will print the pattern
****
***
**
*
Expand|Select|Wrap|Line Numbers
- int linecount = 4;
- while (linecount>0)
- {
- int starcount = linecount;
- while (starcount>0)
- {
- System.out.print("*");
- starcount--;
- }
- System.out.println();
- linecount--;
- }
A shorthand form exists: the for loop
Expand|Select|Wrap|Line Numbers
- for(initialisation;condition;housekeeping)
(2) Following that the loop body is executed and then the housekeeping is done, followed by the test again.
e.g. to display a block of *'s
Expand|Select|Wrap|Line Numbers
- public class Block1
- {
- public static void main(String argv[])
- {
- for (int i=5;i>0;i--)
- {
- for (int j=4;j>0;j--)
- System.out.print('*');
- System.out.println();
- }
- }
- }
The condition is tested at the end of the loop: a useful structure for the times when a loop body must always be done at least once.
For example, the value epsilon is specified thus:
Expand|Select|Wrap|Line Numbers
- 1.0 + epsilon != 1.0
Expand|Select|Wrap|Line Numbers
- epsilon = 1.0
- do
- epsilon = epsilon / 2.0
- while ( 1.0 + epsilon != 1.0 )
- epsilon = 2.0 * epsilon
Expand|Select|Wrap|Line Numbers
- public class epsilon
- {
- public static void main(String s[])
- {
- float epsilon = 1.0f;
- do
- epsilon = epsilon / 2.0f;
- while ((1.0f + epsilon) != 1.0f);
- System.out.println(" float epsilon calculated = " + epsilon * 2.0f);
- }
- }