4. Circulation structure
4.1, circular structure statement
It can execute a piece of code repeatedly when the conditions are met. This repeatedly executed code is called a loop body statement. When the loop body is executed repeatedly, the judgment condition of the loop needs to be changed to false at an appropriate time to end the loop, otherwise the loop will continue to execute and become an dead loop.
4.2. Composition of circular structure statements
- Initialization statement:
One or more statements to complete some initialization operations - Judgment condition statement:
Is a boolean type expression that determines whether the loop body continues to execute - Loop body statement:
It's the code we have to execute many times - Control condition statement
This statement is executed after each cycle and before the execution of the next cycle judgment condition.
Used to control the variables in the loop condition, which can make the loop end at the right time
4.3 classification
- for loop
- while Loop
- do... while loop
4.3.1 for loop
- Format:
1 2 3
For (initialization statement; judgment condition statement; control condition statement){
4
Loop body statement;
}
1243243243243... Until the condition is false and the cycle ends - Execution process
a: Execute initialization statement
b: Execute the judgment condition statement to see whether the result is true or false
If false, the loop ends
If true, continue
c: Loop body statement
d: Execute control condition statement
e: Go back to step b and continue - Look at the picture
//Demand: I want to output 10 times on the console. I love you //I want to output 1000 times? 100000 times? //At present, this method is obviously inappropriate class Demo3{ public static void main(String[] args){ System.out.println("I love you!"); System.out.println("I love you!"); System.out.println("I love you!"); System.out.println("I love you!"); System.out.println("I love you!"); System.out.println("I love you!"); System.out.println("I love you!"); System.out.println("I love you!"); System.out.println("I love you!"); System.out.println("I love you!"); //The above is the original practice, which is obviously not good. //We can use the loop structure to improve the code System.out.println("--------------------------"); for(int i=1;i<=100;i++){ System.out.println("I love you!"); } } }
- matters needing attention:
Whether the conditional statement is simple or complex, the result must be boolean. If a loop statement is a statement, curly braces can be omitted. If it is multiple statements, it must not be omitted. It is recommended never to omit.
//I want to output numbers 1 to 10 on the console class Demo4{ public static void main(String[] args){ //Original practice System.out.println("1"); System.out.println("2"); System.out.println("3"); System.out.println("4"); System.out.println("5"); System.out.println("6"); System.out.println("7"); System.out.println("8"); System.out.println("9"); System.out.println("10"); System.out.println("-------------------"); //It should be written in a loop for(int i=1;i<=10;i++){ System.out.println(i); } System.out.println("-------------------"); //It should be written in a loop for(int i=0;i<10;i++){ System.out.println(i+1); } } }
//Find the sum of data from 1 to 10 /* analysis: First, two variables are required: A variable is used to store the first addend, which actually saves all the previous data and. The default value should be 0 A variable is used to store the second addend, which is actually the value of each data change */ class Demo5{ public static void main(String[] args){ //Original practice: //System.out.println(1+2+3+4+5+6+7+8+9+10); //Define the first addend int sum = 0; //Get the numbers from 1 to 10 in turn for(int i=1;i<=10;i++){ //This i is the second addend //sum = sum + i; sum += i; /* 0 +1 = 1 1+2 = 3 3+3 = 6 .... */ //System.out.println("sum="+sum); } System.out.println("sum="+sum); } }
/* Find the odd sum between 1 and 100 Find the even sum between 1 and 100 */ class Demo6{ public static void main(String[] args){ int sum1 = 0;//Cumulative even sum int sum2 = 0;//Cumulative odd sum //The for loop can get every number between 1 and 100 for(int i=1;i<=100;i++){ //System.out.println("i="+i); //sum += i; //Judge whether i is even if(i%2 == 0){ sum1 += i; }else{ sum2 += i; } } System.out.println("1-100 All even sums between:"+sum1); System.out.println("1-100 All odd sums between:"+sum2); System.out.println("----------------------------------"); //Another approach is to find the sum of even numbers int sum3 = 0; for(int i=0;i<=100;i+=2){ sum3 += i; } System.out.println("1-100 All even sums between:"+sum3); //Ask for odd numbers and write them yourself } }
- Exercise: find the factorial of 10 (you can add keyboard input)
//Factorization of keyboard input number (b) int a = 1; Scanner sc = new Scanner(System.in); int b = sc.nextInt(); for(int i = 1; i <= b ; i++){ a *= i; } System.out.println(b+"Factorial"+a);
/* Output the number of all daffodils on the console Daffodils? It's a three digit number The cubic sum of the numbers in each bit is equal to the number itself 153 It's a daffodil number 1*1*1+5*5*5+3*3*3 = 1+ 125 +27 = 153 analysis: Three digits tell us the range Through the for loop, we can get every three digits The trouble is how to get the three digit number of ten and hundred How do I get the three digit numbers of ten and hundred? Suppose we now get a three digit number 153 Bits: 153% 10 = 3 Ten digit: 153 / 10% 10 = 5 Hundredth: 153 / 10 / 10% 10 = 1 Thousands: x/10/10/10%10 Wan Wei:..... Let one digit * one digit * one digit + ten digit * ten digit * ten digit + hundred digit * hundred digit * hundred digit = = the data itself output */ class Demo7{ public static void main(String[] args){ //Three digits tell us the range for(int i=100;i<1000;i++){ int ge = i%10; int shi = i/10%10; int bai = i/10/10%10; //Let one digit * one digit * one digit + ten digit * ten digit * ten digit + hundred digit * hundred digit * hundred digit = = the data itself if((ge*ge*ge+shi*shi*shi+bai*bai*bai) == i){ //output System.out.println(i); } } } }
- Exercise: count the number of daffodils
//Count the number of daffodils (j) class GeShu{ public static void main(String[] args){ int j = 0; for(int i = 100; i < 1000;i++){ int ge = i % 10; int shi = i / 10 %10; int bai = i / 100 %10; if((ge*ge*ge + shi*shi*shi + bai*bai*bai) == i){ System.out.println(i); j++; } } System.out.println(j); }
- Exercise: Please output and count the data that meets the following conditions
Condition: this data is a number between 1 and 1000
At the same time:
Integer remainder 2 for 3
For 5 integers, the remainder is 3
Divide 7 by 2
class Test{ public static void main(String[] args){ for(int i = 1; i <= 1000; i++){ if(i%3==2 && i%5==3 && i%7==2){ System.out.println(i); } } }
- Exercise: output five digits on the console that meet the following conditions
Conditions:
Bits = 10000 bits
Tens = thousands
One digit + ten digit + thousand digit + ten thousand digit = hundred digit
class Test{ public static void main(String[] args){ for(int i = 1; i < 100000; i++){ int ge = i%10; int shi = i/10 %10; int bai = i/100 %10; int qian = i/1000 %10; int wan = i/10000 %10; if(ge == wan && shi == qian && ge+shi+qian+wan==bai){ System.out.println(i); } } }
4.3.2 while loop
-
Format:
Initialization statement;
While (judgment condition statement){
Loop body statement;
Control condition statement;
} -
Execution process: (same as for)
Go first initialization statement
Take the conditional sentence to see whether it is true or false
False: end of cycle
True: loop statement
Control the conditional statement, and then return to the judgment conditional statement
. . . . .
-Look at the picture
-
Exercise: write all the code of the for loop in while
class Test{ public static void main(String[] args){ /* //Output ten times I love you int i = 1; while(i<=10){ System.out.println("I love you "; i++; } */ //------------------------------------------ //Output 1-10 /* int i = 1; while(i<=10){ System.out.println(i); i++; } */ //------------------------------------------ //Summation 1-10 /* int i = 1; int sum = 0; while(i<=10){ sum += i; i++; } System.out.println(sum); */ //------------------------------------------ //Find 1-100 even sum, odd sum /* int i = 1; int sum1 = 0; int sum2 = 0; while(i<=100){ if(i%2==0){ sum1 += i; i++; } else{ sum2 +=i; i++; } } System.out.println("Even sum: "+ sum1); System.out.println("Odd sum: "+ sum2); */ //------------------------------------------ //Factorial of keyboard input number /* Scanner sc = new Scanner(System.in); System.out.println("Please enter a number: "; int b = sc.nextInt();//keyboard entry int jieCheng = 1; int i = 1; while(i<b){ jieCheng *= i; i++; } System.out.println(b+"The factorial of is: "+ Jiecheng"; */ //------------------------------------------ //Narcissistic number int count = 0;//Number of daffodils int i = 100; while(i<1000){ int ge = i%10; int shi = i/10 %10; int bai = i/100 %10; if(ge*ge*ge + shi*shi*shi + bai*bai*bai == i){ System.out.println(i); count++; } i++; } System.out.println("How many daffodils are there"+count+"individual"); }
4.3.3 difference between for and while
- Although for and while can be converted equivalently, there are some differences
- Use difference:
Control the variable controlled by the conditional statement
After the for loop ends, it cannot be accessed.
After the while loop ends, that variable can still be accessed
If you want to use that variable after the loop ends, use while, otherwise use for
Because the variable disappears from memory after the for loop ends, which can improve memory utilization - Scene difference:
The for loop is suitable for judging a range
The while loop is suitable for operations with unclear judgment times
/* */ class Demo9{ public static void main(String[] args){ //for format for(int i=0;i<10;i++){ System.out.println("I'm a handsome man"); System.out.println(i); } //System.out.println(i);: Error: symbol not found System.out.println("------------------------"); //while format int j = 0; while(j<10){ System.out.println("I'm a handsome man"); j++; System.out.println(j); } //Can continue to visit System.out.println(j); } }
/
* The height of Mount Everest is 8848 m,Suppose I have a piece of paper large enough and the thickness is 0.01m How many times do I have to fold it to ensure that the thickness of the paper is not less than the height of Mount Everest analysis: Define a statistical variable to record the number of folds. The default value is 0 The height of Mount Everest is 8848 m This is the final thickness Suppose I have a piece of paper large enough and the thickness is 0.01m This is the initial thickness How many times do I have to fold? Thickness can exceed 8848 Change every fold? Twice as thick as before As long as the thickness of each change does not exceed 8848, continue to fold, and each fold is a statistical variable++ When it exceeds 8848, it ends and finally outputs statistical variables */ class Demo10{ public static void main(String[] args){ //Define statistical variables int count = 0; //In order to facilitate calculation, the final thickness and initial thickness are expanded by 100 times at the same time //Final thickness //int end = 8848; int end = 884800; //Initial thickness //int start = 0.01; int start = 1; //Stop as long as the thickness of the paper exceeds 8848 while(start<end){ //As long as the thickness does not exceed 8848, it needs to be folded once, and the statistical variables will be changed++ count++; //Thickness change per fold start *= 2; //After adding the statement, you can output the results here System.out.println("The first"+count+"The thickness of the secondary is:"+start); } //Output statistical variable System.out.println("It's folded altogether"+count+"second"); } }
4.3.4 do... while loop
- Format:
Initialization statement;
do{
Loop body statement;
Control condition statement;
}While (judgment condition statement); - Execution process:
Initialization statement
Loop body statement;
Control condition statement
Judge conditional statements to see whether the result is true or false
False: end of cycle
True: loop statement
Return to control condition statement
Continue to judge the conditional statement to see whether the result is true or false
...
-Look at the picture
/* Output 10 times Longge */ class Demo11{ public static void main(String[] args){ int i = 0; do{ System.out.println("Brother long"); i++; }while(i<10); System.out.println("--------------------"); //Find the sum of 1-10 int sum = 0; int a = 1; do{ sum += a; a++; }while(a<=10); System.out.println("sum="+sum); } }
- Exercise: write the previous exercise in do... while
4.4 differences between circular statements
- The do... while loop will execute the loop body statement at least once (the loop body is walked first and then judged)
- for and while loops first judge whether the condition is true, and then decide whether to execute the loop body.
- When using, give priority to for, followed by while, and finally do... While
***No matter whether the condition is true or not, the loop must be executed at least once. Only in this case can do... while be used
class Demo12{ public static void main(String[] args){ int i = 5; while(i<5){ System.out.println("I love brother long."); i++; } System.out.println("------------------------"); int j = 5; do{ System.out.println("I love silence."); j++; }while(j<5); } }
4.5 precautions:
- Pay attention to the dead cycle.......
Be sure to pay attention to the variable controlled by the control condition statement. Don't lose it, otherwise it will be easy to loop. - Two simplest dead loop formats
while(true){ ... } for(;;){...}
class Demo13{ public static void main(String[] args){ /* while(true){ System.out.println("Lala "); } */ /* for(;;){ System.out.println("La La La.... "); } */ int i = 0; while(i<10){ System.out.println(i); i++; //Don't forget this } } }
5. Circular nesting
5.1, loop nesting:
That is, the loop body of the loop statement itself is a loop statement
- Through the following case
The outer loop controls the line
The inner loop controls the columns
/* Requirements: I want to output the following graphics on the console 3 Star chart with 5 rows and 5 columns ***** ***** ***** 5 Row 10 column 100 Row 1000 column ....... */ class Demo14{ public static void main(String[] args){ System.out.println("*****"); System.out.println("*****"); System.out.println("*****"); //Although this completes the requirements, it is not good //With my needs constantly changing, this way can't adapt. //So it needs to be improved //How? //First consider how to print a line of * //System.out.println("*****"); No, it can't meet the needs of change //How to print a* //System.out.println("*"); System.out.println("--------------------"); //System.out.println("*"); //System.out.println("*"); //System.out.println("*"); //System.out.println("*"); //System.out.println("*"); //Now you can print an *, but the line breaks. What do I want to do on one line? //Simple system out. print("*"); Remove ln from println. Ln actually means line feed //System.out.print("*"); //System.out.print("*"); //System.out.print("*"); //System.out.print("*"); //System.out.print("*"); //If you want to print multiple * on one line, it's annoying to write this, and the code is repeated. So you can use loops to improve //Print a * chart with 4 rows and 10 columns //Print first line /* for(int i=0;i<10;i++){ System.out.print("*"); } System.out.println();//Line feed can be realized //Print the second line for(int i=0;i<10;i++){ System.out.print("*"); } System.out.println(); //Print the third line for(int i=0;i<10;i++){ System.out.print("*"); } System.out.println(); //Print the fourth line for(int i=0;i<10;i++){ System.out.print("*"); } System.out.println(); /* Now the same code appears again, which means that it is not written well. The repeated code should be improved by loop */ for(int j=0;j<4;j++){ for(int i=0;i<10;i++){ System.out.print("*"); } System.out.println(); } } }