Day 4: loop structure (while, do... While,)

Source: Internet
Author: User
1. Loop Structure (while, do... While,)

1.1. What is a loop structure

In daily life, there will be a lot of things that need to be done repeatedly, such as four seasons of every year, 7 days of every week, 3 meals a day, and 50 copies of each printer document, three laps of a runway of 400 meters are repeatedly executed.

Let's look at the requirements in the software system:

Question 1: output 100 rows of statements, each line of statements is the same, that is:

  • Action is the step of success. The more actions you take, the higher you enter!
  • Action is the step of success. The more actions you take, the higher you enter!
  • Action is the step of success. The more actions you take, the higher you enter!

...

Question 2: output 100 rows of statements, each line of statements is similar, that is:

  • 1st. Action is the step of success. The more actions you take, the higher you enter!
  • 2nd. Action is the step of success. The more actions you take, the higher you enter!
  • 3rd. Action is the step of success. The more actions you take, the higher you enter!
  • ...
  • 100th. Action is the step of success. The more actions you take, the higher you enter!

Question 3: Calculate the result of multiplying 1 to 50 by 8.88

  • 1 × 8.88 = 8.88
  • 2 × 8.88 = 17.76
  • 3× 8.88 = 26.64
  • 4 × 8.88 = 35.52
  • ...
  • 50 × 8.88 = 444

Such problems are implemented repeatedly, and can be solved through the loop syntax structure in the software system. A loop is a computer processing process that repeatedly executes some code in a programming language. It is a set of identical or similar statements that are regularly executed repeatedly.

For a loop, two elements need to be considered. One element is the loop body, that is, the same or similar statements that are repeatedly executed, and the other element is the loop condition, that is, the condition that the loop can continue to be executed is often reflected by the number of cycles.

Common loop structures include while, do-while, and.

1.2. While statement

1.2.1. Execution logic of the while statement

While statements are a common syntax structure of loops. The syntax is as follows:

 
While (Boolean expression) {statement block ;}

 

When a while statement is executed, the value of the Boolean expression is calculated and then determined. If the value is true, the statement block is executed. After the statement block is executed, the value of the Boolean expression is determined again, if it is true, the statement block will be executed again and again until the value of the Boolean expression is false and the while loop is exited and the statement after the while clause is executed.

1.2.2. While statement Flowchart

As shown in the flowchart-11 of the while statement, it is important to note that, in general, loop operations may make the loop condition not meet, otherwise the loop will become an "endless loop ". "Endless loop" means that the operations on the loop body will always be executed, and the statements after the loop will never be executed. "endless loop" needs to be avoided in the software system.


Figure-11

1.2.3. the while statement is used to process the loop logic.

While statements are widely used in practical applications. The following example shows the execution logic of while statements:

Int age = 1; while (age <= 100) {system. Out. println ("money now"); age ++ ;}

 

The preceding statement is executed as follows. First, declare the integer variable Age and assign the initial value to 1. Then, determine whether the age is less than or equal to 100 and the condition is true, output "money now" and increase the value of age by 1 to 2. Then, judge the condition again. Age is 2, which is still less than 100, output "money now" again, increase the value of age by 1 to 3, and so on until age is equal to 101, the condition is false, and the loop ends.

1.2.4. Use the break statement to exit the loop

Break is used in the loop body to exit the loop structure. See the following sample code:

int x = 0;while ( x < 10 ) {        if ( 5 == x )    {            break;    }        System.out.println(x);        x + + ;}

 

The above code is analyzed to conclude that the output result is 0 1 2 3 4, because when X is equal to 5, the break statement is executed to exit the loop structure directly, that is, the value of output X after the if statement block and X ++ are no longer executed.

1.3. Do-while statement

1.3.1. Execution logic of the do-while statement

The do-while statement is also a common syntax structure of loops. The syntax is as follows:

Do {statement block} while (Boolean expression );

 

The execution process of the do-while statement is: Execute the statement block first, and then judge the Boolean expression. If it is true, execute the statement block again, so that the loop repeats, until the value of the Boolean expression is false. That is to say, the do-while statement executes the statement block once no matter whether the Boolean expression is true or not.

1.3.2. flowchart of the do-while statement

As shown in the flowchart-12 of the do-while statement, like the while statement, the do-while statement should also avoid "Endless loops.


Figure-12

1.3.3. the do-while statement is used to process the loop logic.

The do-while statement is widely used in practical applications. The following example shows the execution logic of the do-while statement:

Int PWD; do {system. Out. Print ("Enter Password"); Pwd = response. nextint () ;}while (123! = PWD );

 

The preceding statement is executed as follows. First, the integer variable PWD is declared. In the DO statement, the system prompts "Enter Password" and receives user input data and assigns it to PWD, then judge whether 123 is not equal to PWD. If it is true, execute the DO statement block, and so on until 123 is equal to PWD, And the loop ends.

1.3.4. Differences between while and do-while statements

While and do-while are both statements used to execute the loop structure. The difference is that while loops are judged and executed first, while do-while loops are executed first and then judged. Then, when the initial condition does not meet the loop condition, the while loop will not be executed once, And the do-while loop will be executed at least once in any case.

Note: The difference between the while and do-while statements is only reflected in the loop that does not meet the conditions for the first time. If this is not the case, the while and do-while statements can be exchanged. See the following two sample programs:

// Example 1: while loop mode int Pwd = 0; while (123! = PWD) {system. out. print ("Password:"); Pwd = cipher. nextint ();} // Example 2: Do-while loop int PWD; do {system. out. print ("password"); Pwd = cipher. nextint ();} while (123! = PWD );

 

Analysis example 1 and Example 2 draw a conclusion that the running results are exactly the same. This is because the first while condition of the two sections of code is met. At this time, while and do-whlie can be exchanged, so the result is exactly the same.

1.4. For statement

1.4.1. Consider the similarities of the following cyclical issues

Consider the similarities of the following three questions:

  1. Calculates the value from 1 to 100;
  2. Computing 1 + 1/3 + 1/5 +... + 1/999;
  3. Find the students whose scores are greater than 90 from 1st to 500th.

We can see from the above question that, for example, all the three questions are performing a regular repetition of an operation, in the program

Consider using the loop structure. First, you need to find the loop variable described above, which regularly changes in each loop and is often used as a condition for determining whether to continue the loop.

First, let's look at the 1st questions and design the Circular Variable I. The value of I is 1, 2 ,..., 100, that is, 1 is increased each time from 1. The second question is to design the cyclic variable I. The value of I is 1, 3, 5 ,..., 999, that is, 2 increases each time starting from 1. The third question is to design the Circular Variable I. The value of I is 1, 2 ,..., 500, that is, 1 is increased each time from 1.

From the above analysis, we can see that the above loop is a fixed number of cycles. In this case, the for statement is preferred.

1.4.2. For statement execution Logic

A For statement is the most commonly used method in a loop. A For Loop is used to repeatedly execute a specified number of statements or statement blocks. Syntax:

  1. For (expression 1; expression 2; expression 3 ){
  2. Statement block (loop body)
  3. }

We can see that the three expressions of the for loop are separated by semicolons (;). The execution logic is as follows:

  1. Calculates the value of expression 1, usually the initial value assigned to the cyclic variable;
  2. Calculate the value of expression 2 (expression 2 is a logical expression), that is, to determine whether the cycle condition is true. If the value is true, the loop body is executed once (statement block); otherwise, the loop jumps out;
  3. Execution cycle body;
  4. Calculates the value of expression 3. Here, the value assignment expression of the updated cyclic variable is usually written;
  5. Calculates the value of expression 2. If the value is true, the loop body is executed. Otherwise, the loop jumps out;
  6. This repeats until the value of expression 2 is false.

1.4.3. Flow chart of the for statement

For statement Flowchart-1:


Figure-1

A simple example is as follows:

for ( int i = 1 ; i <= 10 ; i + + ) {        System.out.println( i );}

 

The output result of the above program is: 1 2 3 4 5 6 7 8 9 10

Analyze the execution process of the above program: first, the initialization I value is 1, judge whether I is less than or equal to 10, the result is true, and secondly, output the I value 1, and then, execute auto-increment 1 of I, then judge whether I is less than or equal to 10, the result is true, the output I value is 2, and so on ...... After the output value of I is 10, execute auto-increment 1 of I. This is 11, the result is false, and the program is terminated.

1.4.4. The for statement is used to achieve a fixed number of cycles.

The for statement is often used to solve the processing of a fixed number of cycles. For example, if you want to accumulate sum and calculate 1 + 2 + 3 +... + 100 of the results are fixed to 100 times. You can use for loop processing. See the following code:

Int sum = 0; For (INT I = 1; I <= 100; I ++) {sum + = I;} system. out. println (sum of "1 to 100" + sum );

 

Analyze the execution process of the above Code. First, declare a variable to save the accumulate sum. This variable is named sum and the initial value is 0. Then, the for loop starts from 1 and increases by 1 each time, run the command 100 times and accumulate the I value into the sum variable in the loop body. Note: I is added based on sum every time, So sum + = I is used. After the loop ends, the sum of the output result "1 to 100" is 5050.

After learning about the above questions, I want to find the factorial of 10, that is, 1*2*3 *... * 10. Can I use the for loop to solve the problem? If so, how can I solve it? Of course. Try !!!

1.4.5. Special usage of the for statement three expressions

First, review the syntax of the for statement:

For (expression 1; expression 2; expression 3) {statement block}

 

The code above shows that the for statement requires three expressions to implement a loop and separated by semicolons,

In actual use, the for statement can be used in several special ways:

Special Method 1: The content at expression 1 is null. See the following code:

Int sum = 0; int I = 1; for (; I <= 10; I ++) {sum + = I;} system. out. println (sum of "1 to 10" + sum );

 

The code above shows that although expression 1 is omitted, it is declared only outside of the for loop, but the position is different. Note that the semicolon before expression 2 cannot be omitted even if expression 1 is not written in the for statement.

Special Method 2: When expression 3 is empty, see the following code:

Int sum = 0; For (INT I = 1; I <= 10;) {sum + = I; I ++;} system. out. println (sum of "1 to 10" + sum );

 

The code above shows that although expression 3 is omitted, it is only placed in the for loop body, but the position is different. Note that the semicolon after expression 2 cannot be omitted even if expression 3 is not written in the for statement.

Special method 3: when the content of expression 1, 2, and 3 is null, see the following code:

For (;) {system. Out. println ("I want to learn ......");}

 

From the code above, we can see that the code above has no cyclic variables and no conditional control, so it will lead to an endless loop, which must be avoided in programming, you can add a break to the loop body to jump out of the loop.

Special Method 4: expression 1 and 3 content diversity

In the for statement, EXPRESSIONS 1 and 3 can use a comma expression. A comma expression is an expression consisting of multiple expressions separated by the "," operator, and is calculated from left to right. See the following example:

 
for ( int i =1 , j = 6 ; i <= 6 ; i +=2 , j -=2 ) {System.out.println(“ i , j = “ + i + “,” + j );}

 

The execution logic of the above Code is as follows: initially set I to 1, J to 6, judge whether I is less than or equal to 6, execute the loop body for true, and then execute I + = 2, j-= 2, that is, I increases 2, and J decreases 2. Then, judge whether I is less than or equal to 6. If it is true, continue to execute the loop body, and so on until the condition is false. The output result of this program is:

i , j = 1 , 6i , j = 3 , 4i , j = 5 , 2

 

1.4.6. Use the break statement in the loop

The break statement in a loop has a wide application rate. Break can be used in loop statements or switch statements. When it is used in a loop, the program can terminate the loop and execute the statements following the loop, it is often used with conditional statements. See the following code:

 
int sum = 0;for(int i=1; i<=100; i++){if(sum>=4000){break;}sum += i;}System.out.println(sum);

 

The above program needs to calculate the sum of 1 to 100, with the condition that when the sum is greater than or equal to 4000, the calculation is terminated. In this case, the for statement exit is implemented by using break in the IF statement, the final sum value of this program is 4005.

1.4.7. Use the continue statement in the loop

The continue statement can only be used in a loop. It is used to skip the remaining statements in the loop body and execute the next loop. See the following code:

 
int sum = 0;for(int i=1; i<=100; i++){if( i % 10 == 3 ){continue;}sum += i;}System.out.println(sum);

 

The above program needs to calculate the sum of 1 to 100, with the condition that all the three digits are skipped, in this case, the remaining loop body statement in the for statement is skipped by using continue in the IF statement. The final sum value of this program is 4570.

Day 4: loop structure (while, do... While,)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.