Loop Basics
It is often necessary to repeat certain blocks of code for a specified(or unspecified) number of times. We use a control structure known as a loop to accomplish this. Every loop has four basic parts:
- Loop control variable declaration/initialization
- Loop condition
- Control variable alteration/reassignment
- Loop body(statements to be repeated)
Loops come in two basic varieties. In PreTest Loops, he condition is tested before the loop execute. This means that if the condition fails, the code in the loop may never execute. The other variety of a PostTest Loop. In these types of loops, the condition is tested after the loop code runs. The code will always run at least once.
Regardless of whether you loop is pre or post test, it also has another type of classification: counting or sentinal. Counting loops are set to execute a certain number of times. Loops that depend on user input are called sentinal loops, and will execute as many times as necessary until the user enters a predefined value.
Finally, Java has two loop keywords that can help control the flow of the loop. Those words are ’break’ and ‘continue.’ Break will immediately send control to the code following the loop. Continue sends control to the top of the loop.
Do...While Loops
A do while loop is a post-test iterative structure that can be used as a counting or sentinal lop. In general, a do-while loop looks like this:
do
{
}while();
Do while loops are often used for data verification as we do not need to do a priming read because the loop will always run at least once. To get a number from the user between 1 and 10, the loop might look like this:
int input;
do
{
input=reader.readInt(“Enter a number between 1 and 10:);
}while(input<1 || input>10)
...