Google
 
Site navigation: [ Home | Theory | Java | Moodle courses | Resource wiki | About ]

Repetition

Repetition is also known as looping and by the more technical term iteration .

Nested loops (2 mastery factors) are used where 2dDstructures (eg matrices or game boards) need to be processed.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Tracing an algorithm is also known as " desk-checking " or " dry-running ". With practice you can spot a lot of potential problems before you write any code.

 

 

 

 

 

 

 

 

 

 

 

 

On this page: [ simple repetiton | trace tables | Exercises | do while ]
[ for next | More exercises ]

Simple repetition

Also called iteration or looping (if else is sometimes known as branching). We have seen the if statement, it is known as a < conditional > statement since the next statement to be executed depends upon the condition in the if part.

    while ( condition )
   {
     java statement(s);
// these are repeated as long as the condition is true
   }

The conditions are the same as for selection statements and can be simple or multiple. Loops can also be nested :

  while ( condition )
   {
     while ( another condition )
     {
        other java statement(s);
     
   // these are repeated as long as <another condition> is true
     }
     java statement(s);
// these are repeated as long as the condition is true
   }

As for selection, the brackets are not always needed but it is considered good programming practice to put them in. Refer to the selection page for details of condition statements and multiple conditions .

back to top

Simple Example

          TextArea somewhere = new TextArea(10, 20);
      int x = 1;
      while (x < 10)
      {
        somewhere.appendText("Hello World!");
        x = x + 2;
      }

How many times is the message written into the text area?

back to top

Trace Tables

Let's trace a loop, trace tables are the best way to determine if your program will do what you want and expect it to do. We'll use a slightly different loop for this example:

   int count = 0;
   int x = 1;
   TextArea display = new TextArea(10, 20);
   while (x < 100)
   {
     display.append("" + x + "\n");
     x = x * 2;
     count = count + 1;
   }
   display.append("The loop ran: " + count + " times\n");

Here is a trace table for you to copy and complete:

 
count
x
x < 100
display.append(x)
 
0
1
true
1
 
1
2
true
2
 
2
4
true
4

How many times did the loop run

Exercises

Write an Applet called Loopy that shows the output of the above algorithm.

If you are stuck, here is a similar example called TheCount. Dedicated to the character from Sesame Street of the same name.

back to top

Common errors in writing loops:

1  Putting the semi-colon after the while do statement:

  while (x != 8);
  {
    somewhere.setText("Hello");
// never done
  }

2  Forgetting to increment the loop:

  int x = 0;
  while (x != 8);
  {
    somewhere.setText("Hello");
    x = x + 1;                  
// easy to forget to do this!
  }

back to top

do while loop

The do while loop places the conditional test at the end, so is like a repeat until loop of other languages:

   while <condition>
   {
     statements
   }

  do
  {
      statements
  } while <condition>;
// notice the semi-colon
condition is at top
loop may never execute

Often a useful feature

condition is at end
loop must execute at least once

equivalent to repeat .. until of
some languages.

In most cases the loops are inter-changeable, either one can be used. In some circumstances the while loop is preferred; we shall see examples of this as we progress through the course.

Exercise - Re-write the 4 example loops of the Pop Quiz as do while loops. Make sure they give the same output.

for next loop

This form of loop is very useful when it is known in advance how many times it will be executed. The for loop has 3 distinct parts : initialization , test and increment :


Initialize involves a statement or expression that sets an initial value, at its simplest we can set a loop counter (a variable to keep track of how many times the loop has executed).

Test will check to see if the stopping condition has been reached, eg has the loop been executed 10 times yet?

Increment will increase (or decrease) the value of the loop counter.

     for ( int i=0 ; i < 10 ; i++ )
   {
      textWindow.append( "\nHello World!");
   }

This loop will set i to zero initially, test the value of i, increase it by 1 then carry out the statement(s) in the body of the loop - thus it will execute 10 times.

It is possible to have different starting points and increments, for example:

  for ( int k=2 ; k <= 10 ; k = k + 2 )

Will go through the sequence 2, 4, 6, 8, 10 before quitting.

More Exercises

Conversion Tables

Build a conversion table, eg of kilos to pounds weight (1 kg = 2.2 lbs) or currencies. Using a for .. do loop construct a conversion table from 2 to 20 kg at 2 kg intervals. Eg:


   Kilos    Pounds
   2         4.4
   4         8.8
   6        13.2


Note that you are allowed to use the loop variable in a calculation but don't ever change it! For example:

   for (int k = 1; k == 15; k++)
   {
     k = k * 2;             
/* don't do this! */
     lbs = k * 2.2;         
/* this is OK */
   }


is a very bad idea . The reason is that the loop doesn't stop until the loop variable (or control variable, k in this case) is equal to the terminating value (15 in this case). Since k is doubled each time round the loop it will never be equal to 15 and the loop will not terminate (unless you reset the computer or can break the program some other way).

Widgets

A factory is turning out widgets at the rate of 1200 per month. Production is planned to increase at 10% each month until production has reached or exceeded 1750 per month. How many months will this take?

Patterns

Using the same basic format as the TheCount Applet try to make some interesting patterns in a TextArea using a while loop or loops, some examples:

Triangle

*
**
***
****
*****

Diamond

       *
      ***
    *****
      ***
        *

Related: [ Java Core | previous selection quizzes | next:The Count ]

Loops


 
The site is partly financed by advertising revenue, partly by online teaching activities and partly by donations. If you or your organisation feel these resouces have been useful to you, please consider a donation, $9.95 is suggested. Please report any issues with the site, such as broken links, via the feedback page, thanks.

Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy.

Creative Commons License


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2009 Richard Jones, PO BOX 246, Cambridge, New Zealand;
This page was last modified: May 31, 2009