1. Circular structure
A loop statement can repeatedly execute a certain piece of code when the loop condition is met. This repeated code is called a loop body statement. When this loop body is repeatedly executed, the loop judgment condition needs to be modified to false at the appropriate time to end the loop, otherwise the loop will continue to execute, forming a dead loop.
Composition of loop statements:
Initialization statement: One or more statements, these statements complete some initialization operations.
Decision conditional statement: This is a boolean expression, which can determine whether to execute the loop body.
Loop-body statement: This part is a loop-body statement, which is what we have to do many times.
Control condition statement: This part is executed before the next cycle judgment condition is executed after the end of the cycle body. By controlling the variables in the loop condition, the loop ends at the appropriate time.
eg: When "HelloWorld" is output 10 times on the console,
Initialization statement: Define initialization as the first time.
Judgment conditional statement: The number of times cannot exceed 10 times.
Loop body statement: output the "HelloWorld" statement.
Control condition statement: The number of times changes to the next time.
2. Loop structure (for loop statement)
For loop statement format:
for(initialization statement; judgment conditional statement; control conditional statement) {
Loop body statement;
}
Execution process:
A: Execute the initialization statement
B: Execute the judgment conditional statement to see if the result is true or false: if it is false, the loop ends; if it is true, continue to execute.
C: Execute loop body statement
D: Execute control condition statement
E: Go back to B and continue
flow chart:
Notes:
(1) The result of the judgment conditional statement is a boolean type
(2) If the loop statement is a single statement, the braces can be omitted; if it is multiple statements, the braces cannot be omitted. It is recommended not to omit it.
(3) Generally speaking: if there is a left brace, there is no semicolon, if there is a semicolon, there is no left brace.
Example code:
1. Find the sum of even numbers between 1-100:
/* Requirements: A: Find the sum of 1-100. B: Find the sum of even numbers between 1-100*/class ForTest1 { public static void main(String[] args) { // Find the sum of 1-100. int sum1 = 0; for(int x=1; x<=100; x++) { sum1 +=x; } System.out.println("1-100 is: "+sum1); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //Method 2 int sum3 = 0; for(int x=0; x<=100; x+=2) { sum3 += x; } System.out.println("1-100 even numbers are: "+sum3); System.out.println("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------2. Find the factorial of 5:
/* Requirement: Find the factorial of 5. What is factorial? n! = n*(n-1)! Rule n! = n*(n-1)*(n-2)*...*3*2*1 Sum ideology. Find factorial thought. */class ForTest2 { public static void main(String[] args) { //Define the final result variable int jc = 1; //The x here can actually start directly from 2//for(int x=1; x<=5; x++) for(int x=2; x<=5; x++) { jc *=x; } System.out.println("1-5 factorial is: "+jc); }}3. Output all "Narcissus Number" in the console:
/* Requirements: Output all "Narcissus numbers" on the console Analysis: We don't know what "Narcissus numbers" is, what do you ask me to do? The so-called Narcissus numbers refer to a three-digit number, and the cube sum of their digits is equal to the number itself. For example: 153 is a daffodil. 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153 A: The three-digit number actually tells us the range. B: Through the for loop, we can obtain each triple digit number, but the trouble is how to obtain the data of this triple digit number, ten, and hundreds. How do we obtain the data of a data, ten, and hundreds? Suppose there is a data: 153 ge: 153%10 = 3 shi: 153/10%10 = 5 bai: 153/10/10%10 = 1 qian: x/10/10/10%10 wan: x/10/10/10/10%10 ... C: Let ge*ge*ge+shi*shi*shi+bai*bai*bai compare with the data, and output the data on the console. */class ForTest3 { public static void main(String[] args) { //The triple digit actually tells us the range. for(int x=100; x<1000; x++) { int ge = x%10; int shi = x/10%10; int bai = x/10/10%10; //Let ge*ge*ge+shi*shi*shi+bai*bai*bai compare with the data if(x == (ge*ge*ge+shi*shi*shi+bai*bai)) { //If the same, output the data on the console. System.out.println(x); } } }}3. Loop structure (while loop statement)
While loop statement format:
while(judgment conditional statement) {
Loop body statement;
}
//Extended format initialization statement;
while(judgment conditional statement) {
Loop body statement;
Control condition statement;
}
flow chart:
The difference between a for loop and a while loop:
For loop statements and while loop statements can be converted equivalently, but there are still some small differences.
(1) Differences in use:
The variable controlled by the control conditional statement cannot be accessed after the for loop ends, and can continue to be used after the while loop ends. If you want to continue using it, use while, otherwise it is recommended to use for. The reason is that the for loop ends and the variable disappears from memory, which can improve the efficiency of memory usage.
(2) Scene difference:
For loop is suitable for operation for a range judgment while loop is suitable for operation for unclear number of judgments
Example code:
The highest mountain in our country is Mount Everest: 8848m. I now have a large enough paper with a thickness of: 0.01m. May I ask, how many times I fold it to ensure that the thickness is not lower than the height of Mount Everest?
/* The highest mountain in our country is Mount Everest: 8848m. I now have a large enough paper with a thickness of: 0.01m. May I ask, how many times I fold, I can ensure that the thickness is not lower than the height of Mount Everest? Analysis: A: Define a statistical variable, the default value is 0 B: The highest peak is Mount Everest: 8848m This is the final thickness. I now have a large enough piece of paper, with a thickness of: 0.01m This is the initial thickness C: How many times I fold, I can ensure that the thickness is not lower than the height of Mount Everest? What changes will happen if I fold it once? That is, the thickness is twice as thick as before. D: As long as the thickness of each change does not exceed the height of Mount Everest, it will be folded, statistical variable ++ E: Output statistical variables. */class WhileTest01 { public static void main(String[] args) { //Define a statistical variable, the default value is 0 int count = 0; //The highest peak is Mount Everest: 8848m This is the final thickness//I now have a paper that is large enough, with a thickness of: 0.01m This is the initial thickness//For simplicity, I turned 0.01 into 1, and the same way 8848 became 884800 int end = 884800; int start = 1; while(start<end) { //As long as the thickness of each change does not exceed the height of Mount Everest, fold it, and the statistical variable ++ count++; //What changes will happen if it is folded once? It is that the thickness is twice the previous one. start *= 2; System.out.println("th"+count+"thickness is "+start); } //Output statistical variables. System.out.println("to be stacked"+count+"time"); }}4. Loop structure (do…while loop statement)
Basic format:
do {
Loop body statement;
}while((Judgement Conditional Statement);[/code]
Extended format:
Initialization statement;
do {
Loop body statement;
Control condition statement;
} while((Judgement Conditional Statement);[/code]
flow chart:
5. Differences and precautions for cyclic structure:
The three loop statements can actually complete the same function, which means that they can convert equivalently, but there are still small differences:
The do…while loop will execute the loop body at least once. For loop and while loop will only execute the loop body when the condition is true
1. Notes:
When writing programs, you should give priority to the for loop, then consider the while loop, and finally consider the do...while loop.
The following code is a dead loop:
while(true){}
for(;;){}
2. Nested use of loops: the loop body of the loop statement itself is a loop statement
(1) Question 1: Please output a star (*) pattern with 4 rows and 5 columns:
Tip: The number of rows controlled by the outer loop, and the number of columns controlled by the inner loop
/* Requirements: Please output the following shape* ** *** **** **** ** ***** Tip: The outer loop controls the number of rows, the inner loop controls the number of columns*/class ForForTest01 { public static void main(String[] args) { // Through a simple observation, we see that this is a row is 5 and the number of columns is a changing shape//We first print out a shape of 5 rows and 5 columns for(int x=0; x<5; x++) { for(int y=0; y<5; y++) { System.out.print("*"); } System.out.println(); } System.out.println("---------------------------------------------------------); //We have implemented a shape of 5 rows and 5 columns//But this is not what we want //What we want is the change of the number of columns//How does the number of columns change? //The first row: 1 column y=0,y<=0,y++ //The second row: 2 column y=0,y<=1,y++ //The third row: 3 column y=0,y<=2,y++ //The fourth row: 4 column y=0,y<=3,y++ //The fifth row: 5 column y=0,y<=4,y++ //When looking at the change of x in the outer loop, it happens to be x=0,1,2,3,4 //So the final version of the program is as follows for(int x=0; x<5; x++) { for(int y=0; y<=x; y++) { System.out.print("*"); } System.out.println(); } }}(2) Question 2: Output the nine-nine multiplication table on the console:
/* Requirements: Output the nine-nine multiplication table in the console. First we write the nine-nine multiplication table: 1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=9 1*4=4 2*4=8 3*4=12 4*4=16 ... 1*9=9 2*9=18 3*9=27 ... Let's first see this nine-nine multiplication table as such: * ** ********* ********* ********* ********* ********* ********* Note: '/x' x means any, this method is called transfer characters. '/t' The position of a tab character (tabtab key) '/r' Enter '/n' line break */class ForForTest02 { public static void main(String[] args) { for(int x=0; x<9; x++) { for(int y=0; y<=x; y++) { System.out.print("*"); } System.out.println(); } System.out.println("---------------------"); //To use data, we start from 1 for(int x=1; x<=9; x++) { for(int y=1; y<=x; y++) { System.out.print(y+"*"+x+"="+y*x+"/t"); } System.out.println(); } }}Running effect:
6. Jump control statement:
As we have already said before, goto in Java is a reserved word and cannot be used at present. Although there is no goto statement to enhance the security of the program, it also brings a lot of inconvenience. For example, I want to end when a certain loop knows to a certain step, and I can't do this now. In order to make up for this defect, Java provides break, continue and return to control jumps and interrupts of statements.
break interrupt
continue
return
1. Jump control statement (break):
Use scenarios for break:
~ In the switch statement for selecting structure
~In the loop statement (if judgment is added to the loop statement)
Note: It is meaningless to leave the use scenario
The function of break:
A: Break out of the single-layer loop
B: Break out of multi-layer loop
To achieve this effect, you must know something. A statement with label. Tag names must comply with Java naming rules
Format:
Tag name: statement
Example code:
/* Control jump statement: break: interrupt continue: continue: return: return break: interrupt meaning usage scenario: A: switch statement B: loop statement. (If judgment is added to the loop statement) Note: It is meaningless to leave the above two scenes. How to use it? A: Break out of a single-layer loop B: Break out of a multi-layer loop To achieve this effect, you must know something. A statement with label. Format: Tag name: Statement */class BreakDemo { public static void main(String[] args) { //Offset outside switch or loop//break; //Offset a single-layer loop for(int x=0; x<10; x++) { if(x == 3) { break; } System.out.println("HelloWorld"); } System.out.println("over"); System.out.println("---------------"); //Offset a multi-layer loop wc:for(int x=0; x<3; x++) { nc:for(int y=0; y<4; y++) { if(y == 2) { //break nc; break wc; } System.out.print("*"); } System.out.println(); } }}In line 38, we add a tag to the outer loop called wc, and then jump out of this tag in line 42.
Running effect:
Note: In actual development, the function of jumping multi-layer looping is almost impossible to use.
2. Jump control statement (continue):
Use scenarios for continuing:
There is no point in leaving the use scenario in a loop statement
The difference between continue and break:
break Break out of single-layer loop continue Break out of a loop and enters the next execution.
The effects are as follows:
Interview questions:
for(int x=1; x<=10; x++) { if(x%3==0) { //Fill in the code here} System.out.println("Java Learning"); }Fill in line 4 of the above code to satisfy the following conditions:
I want to output 2 times in the console: "Java Learn" break;
I want to output 7 times in the console: "Java Learning" continue;
I want to output 13 times in the console: "Java Learning" System.out.println("Java Learning");
3. Jump control statement (return)
The return keyword is not to jump out of the loop body. The more commonly used function is to end a method, that is, exit a method and jump to the method called in the upper layer.
To put it bluntly: the function of return is not to end the loop, but to end the method.
The effects are as follows:
Exercises of loop statements combined with break:
Interview question: Xiaofang's mother gives her 2.5 yuan a day, and she will save it. However, whenever this day is the 5th day of saving or a multiple of 5, she will spend 6 yuan. How many days can Xiaofang save it to 100 yuan.
Code implementation:
/* Requirements: Xiaofang's mother gives her 2.5 yuan a day, and she will save it. However, whenever this day is the 5th day of saving or a multiple of 5, she will spend 6 yuan. How many days can Xiaofang save it to 100 yuan. Analysis: A: Xiaofang's mother gives her 2.5 yuan a day, double dayMoney = 2.5; B: She will save double daySum = 0; C: Store int dayCount = 1 from the first day; D: How many days will Xiaofang save 100 yuan. double result = 100; E: If this day is the 5th day of saving or multiple of 5, she will spend 6 yuan, indicating that she needs to judge the value of dayCount. If the 5 is divided, 6 yuan will be subtracted. daySum -= 6; This also implies a problem, that is, if it is not a multiple of 5 days, the money must be accumulated daySum += dayMoney; F: Because I don’t know how many days it is, I use a dead loop. Once it exceeds 100 yuan, I will exit the loop. */class WhileDemo { public static void main(String[] args) { //The money to be stored every day is 2.5 yuan double dayMoney = 2.5; //The initialization value of saving is 0 double daySum = 0; //Storage int dayCount = 1 from the first day; //The final storage is no less than 100 and the int result = 100; //Because I don’t know how many days it is, I use a dead loop, while(true) { //Accumulate money daySum += dayMoney; //Once it exceeds 100 yuan, I exit the loop. if(daySum >= result) { System.out.println("Spending a total of 100 yuan in storage in total"); break; } if(dayCount%5 == 0) { //Spend 6 yuan daySum -= 6; System.out.println("Things"+dayCount+"Spending a 6 yuan in total"); } //The number of days changes dayCount++; } }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.