IT Band of Brothers Java Grammar loop flow control statements sentence structure 2

Double for loop

If a loop in the other loop, then it can form a nested loop, i.e. for the double loop, nested loops may of course also be nested for loop while loop, while loop may be nested while loops ... ..., i.e., various types of cycle can be used as the outer loop, the inner loop as can be.

When the program encounters a nested loop, the outer loop of the loop condition if allowed, the outer loop iteration of the loop begins, and will be the inner loop to outer loop iteration of the loop - the inner loop only requires repeated implement their own loop only. When the loop condition the inner loop execution ends, and the outer loop execution loop, the outer loop is calculated again to determine whether the outer loop iteration of the loop begins again.

According to the above analysis, it is assumed for the outer loop n times the number of cycles, the number of inner loop cycle m times, then the loop of the inner loop, there are actually nxm times. Nested loop execution process shown in Figure 4.14:

From the point of view of FIG., The inner loop is a nested loop as the loop of the outer loop. When only the inner loop of the loop condition is false, it will be completely out of the inner loop, we can end when the outer loop cycles, the next cycle begins. The following is a classic example code for a double loop in the console Printing triangle:

public class ForDemo3{

    public static void main(String[] args){

         for(int i = 0; i <= 5; i++){

              for(int j = 0; j < i; j++){

                   System.out.println("*");

              }

              System.out.println(" ");

         }

    }

}

a60a76fa5aed4b0d87dc797ec40904c0.png

14 for dual loop

 

Compile and run this program, the console 15 displays information as shown in FIG.

32bc6b99216c4e1eb434d7fab60ee931.png

FIG 15 ForDemo3 operating results

 

Of course, not only in the circulation loop can be nested layer, is theoretically unlimited nested loop nest but if too much, then, will affect the performance of the program, and it will be very difficult to read, so development should be avoided deeper nested loop.

Guess you like

Origin www.cnblogs.com/itxdl/p/11261992.html