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

Source: Internet
Author: User

Day 4: loop structure (while, do... While, ),... While
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(“get money soon”);
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 {
pwd = scanner.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
int pwd = 0;
while (123! = pwd) {
pwd = scanner.nextInt ();
}
// Example 2: do-while loop
int pwd;
do {
pwd = scanner.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(“1到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 ("The sum of 1 to 10 is:" + 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 ("The sum of 1 to 10 is:" + 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 (;;) {
System.out.println ("I want to learn ...");
}
```

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 , 6
i , j = 3 , 4
i , 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(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 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.

Three types of loop structures (while, do-while, for loop): What are the values of an odd number within 1000?

Is it VB?
Dim I As Integer
I = 1
While I <1, 1000
S = s + I
I = I + 2

I = 1
Do
S = s + I
I = I + 2
While I <1, 1000

I = 1 (s = 0)
For 1 to 999
S = s + I
I = I + 2
Next I

What are the differences in the while do while for if loop structure in C?

While is the first to judge the code below, do while is the first to run and then judge, for usage is more flexible a bit like do while, if it is good to understand, it is just a judgment, in the future, many algorithms will be used flexibly.

Related Keywords:
Related Article

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.