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.
For Loops
A for loop is a pretest iterative structure used most often as a counting loop. It also combines three of the four loop requirements into one line. The general form of a for loop is:
for(; ; ){
}
Here is an example of a for loop that counts to 10 and displays the information on the screen:
for(int count=1; count<=10; count++){
System.out.println(x);
}
It is important to note that in Java, a variable's scope (the part of the program in which it is valid), is determined by where it is declared. If you declare a variable as part of a for loop, it will NOT be available outside (after) the loop. Thus, it is sometimes advantageous to declare the variable before the loop and simply initialize it in the loop.
Nested Loops
It should be noted that like all programming control structures, loops can be nested within each other to produce more complex code. Similarly, loops can appear in conditional structures, and vice-versa. Below, is an example of a nested loop that produces a table of values from 1-28, organized into 4 rows and 7 columns.
for(int r=1; r<=4; r++){
for(int c=1; c<=7; c++){
System.out.print(r*c+" ");
}
System.out.println(); //move cursor to new line at end of row
}
The outer loop will execute 4 times. The inner loop will execute 7 times for EACH execution of the outer loop, or a total of 28 times.