Repetition or Iteration
The third control structure allows us to repeat parts of a program. The first form is
- while (some condition) do something
Where the condition is written using comparison operators.
e.g. print a line of *
-
-
public class Line
-
{
-
public static void main(String argv[])
-
{
-
int i=5;
-
while (i>0)
-
{
-
System.out.print('*');
-
i--;
-
}
-
System.out.println();
-
}
-
}
-
A loop may contain any code required, including another loop with each level of nesting is indented further so that the structure is immediately visible.
e.g. A nested loop that will print the pattern
****
***
**
*
-
int linecount = 4;
-
while (linecount>0)
-
{
-
int starcount = linecount;
-
while (starcount>0)
-
{
-
System.out.print("*");
-
starcount--;
-
}
-
System.out.println();
-
linecount--;
-
}
-
A loop has several distinct parts: initialisation (linecount = 4), condition (linecount>0), loop body and 'housekeeping' (linecount--).
A shorthand form exists: the for loop
- for(initialisation;condition;housekeeping)
(1) Initialisation is done before the loop starts, then the condition is tested.
(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
-
-
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 do loop
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:
The value of epsilon is the smallest number which, when added to the value 1.0, changes the value, i.e. adding any smaller value to 1.0 still gives 1.0. A pseudo-code version of the algorithm often used to calculate the values of epsilon is:
-
epsilon = 1.0
-
do
-
epsilon = epsilon / 2.0
-
while ( 1.0 + epsilon != 1.0 )
-
epsilon = 2.0 * epsilon
-
which can be implemented in Java using a do loop
-
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);
-
}
-
}