1. While loop
while (condition) { dosomething (); }
Condition: Conditions for Loop Formation (Boolean)
DoSomething (): Loop execution Event
When conditions are always true: Dead loops
Note two points:
- Must have a conditional variable, and the condition variable must be initialized
- To dynamically change the value of the cyclic condition inside the loop body
// ask for a number of the sum of everyone int num = 456789; int sum = 0; while (num!=0) { + =num%10 ; /=; } SYSTEM.OUT.PRINTLN (sum);
2. For loop
for (initialize; cycle condition; Update operation) { dosomething (); }
The For loop parenthesis contains three executable statements. The first one is used for initialization, which executes when the loop is just beginning to enter. The second is the condition of the loop, which is generally a Boolean expression. The third update operation is performed for the loop, which is executed once in each loop. Three statements can be omitted, while omitting the structure of the super-loop body, that is, the dead loop.
// sum of all integers within 1 to 100 that can be divisible by 3 int sum = 0; for (int i = 0; I <=; i++) { if(i%3==0) { + = i; } } SYSTEM.OUT.PRINTLN (sum);
Strengthen for loop (foreach)
for (E e:eary) { dosomething (); }
The strengthen for loop consists of declaring statements and accessing the array two parts, declaring statements used to declare local variables, and the type must be the same as the array name used to iterate through each element in the array.
// prints information about all the elements in the list for (Student student:list) { student.showinfo ();}
3. Do...while Cycle
Do { dosomething (); } while (condition);
In some cases, we want to enter the same cycle as the condition is not satisfied, and then we can use the Do...while loop.
The Do...while loop is a judgment that is performed after each execution of the loop body, so that the loop content is executed at least once.
4, break, continue keywords
Break: Used to jump out of a single-layer loop, after break the statement will not be executed, after the break statement execution, the loop will be terminated;
Continue: Used to jump out of a single cycle, continue after the statement will not be executed, continue statement execution, the loop is not terminated, the next loop to start the execution.
2nd. Loops in Java