Sunday, May 20, 2007

Repetition Structure

This week we continue with the 3rd control structure of programming, namely Repetition Structure.

Repetition structure is used to make certain portions of the program code run repeatedly, to achieve certain logic that you want. There are 3 Java statements to do repetition, while(), for() and do-while(). Refer to your lab 4 or the textbook for the syntax.

The characteristics for these loops are:

while() loop:
  • this is a pre-test loop, meaning the condition is tested before going into the loop.
  • for a counter-controlled loop, need to specify the starting value for the counter (int i = 0;), the continuation condition (while(i<5)) and the increment (i++;). The starting value is to be specified before the loop, and the increment is to be within the loop.
  • for a sentinel-controlled loop, need to ensure that the value to be checked/compared against the sentinel value is being changed within the loop, either by some calculations, or by requesting input from the user.
for() loop:
  • a for() loop works exactly the same as a counter-controlled while() loop by collecting all the 3 necessary statements and putting them together in the for() statement.
  • a for() loop is particularly useful when we are dealing with arrays.
do-while() loop:
  • a do-while() loop is a post-test loop, meaning the statements within the loop is ran first before the condition is checked/tested if the loop is to be repeated.
  • the only difference between do-while() loop and while() loop is that statements are ran at least once for a do-while() loop, and statements may not be ran at all for a while() loop.
  • for the while() statement in a do-while() loop, you need to put a semi-colon (;) at the end of the statement.
That's about the important things that you should take note.

No comments: