Logic of the computer program (10)-Powerful cycle "turn"

Source: Internet
Author: User

Cycle

In the previous section we introduced the conditional execution in process control and performed different actions depending on the specific conditions. In this section we describe loops in process control, where the so-called loops are repeated to perform certain similar operations, which are generally not identical operations, but similar operations. What are the operations? There are too many examples of this.

    • Show photos, we look at the photos on the phone, the program behind the need to show the photos to us.
    • Play the music, we listen to the music, behind the program follow the playlist first to let us put.
    • View the message, we browse the friend Circle message, behind the program will show the message to us.

In addition to repeating reading or displaying the contents of a list, many of the operations in the daily cycle are done by loops.

    • In a file, looking for a word, the program needs to be compared with the words in the file (although there may be a more efficient way, but also without loops).
    • Use Excel to summarize data, such as sums or averages, and to cycle through the data for each cell
    • Mass blessing message to friends, the program needs to cycle to each friend hair.

Of course, these examples are just the tip of the iceberg, computer programs can only be run in sequence execution, conditional execution and loop execution, the order and conditions are actually nothing special, and the loop is probably the most powerful place. With loops, computers can do things that are difficult or impossible to accomplish very efficiently, for example, to find documents containing a search term in a large number of files, to summarize hundreds of thousands of sales data, and so on.

In Java, there are four forms of loops, namely while, Do/while, for, and foreach, let's look at them separately.

While

The syntax for while is:

While(conditional statement) {    code block}

Or

While and if the syntax is much like, just replace if with the while, it is very simple to express the meaning, as long as the conditional statement is true, always execute the following code, for false stop do. For example:

New Scanner (system.in); SYSTEM.OUT.PRINTLN ("Please input password");  int num = reader.nextint ();  int password = 6789;  while (num!=password) {System.out.println ("Please input password"); num = reader.nextint ();} SYSTEM.OUT.PRINTLN ("correct"); Reader.close ();          

In the above code, we use a reader variable of type scanner to receive a number from the screen console, Reader.nextint () receives a number from the screen, if the number is not 6789, always prompt for input, otherwise just jump out of the loop. (The above code scanner we have not introduced, can ignore its details, and the code is only used to explain the syntax, should not be considered as the actual good code)

In a while loop, code in a block of code affects the loop condition, but often does not know when the loop exits. As shown in the example above, the match will exit but when it can match depends on the user's input.

Do/while

If the code block executes at least once, no matter what the conditional statement is, you can use the Do/while loop. The syntax of Do/while is:

Do{   code block;} While (conditional statement) 

This is also easy to understand, first execute the code block, and then judge the conditional statement, if it is set up, then continue the loop, or exit the loop. That is, the code block executes at least once, regardless of the condition statement. With the above example, its do/while loop is:

New Scanner (system.in);  int password = 6789;  int num = 0;  Do{System.out.println ("Please input password"); num = reader.nextint ();} while (num!=password); SYSTEM.OUT.PRINTLN ("correct"); Reader.close ();           

For

The most widely used loop syntax in practice may be for, especially if the number of cycles is known. The syntax for the for is:

For(initialize statement; loop condition; step operation) {   loop body}

There are two semicolons in parentheses after the for, and three statements are separated, except that the loop condition must return a Boolean type, there is no requirement for the other statements, but usually the first statement is used for initialization, especially the cyclic index variable, and the third statement modifies the loop variable, which is generally stepping, The index variable is incremented or decremented, and the loop body is the statement executed in the loop.

The For loop simplifies writing, but the execution process is not so obvious to beginners, in fact, the process it executes is this:

    1. Execute initialization Instructions
    2. Check if the loop condition is true, and if False, skip to step 6th
    3. Loop condition is true, loop body is executed
    4. Performing a stepping operation
    5. After the step operation is finished, jump to the 2nd step, which is to continue checking the loop condition.
    6. Statements following the FOR loop

Here is a simple for loop:

Int[] arr = {1,2,3,4};  for (int i=0;i<arr.length;i++) {    System.out.println (arr[i]);}   

Sequentially prints each element in the array, initializes the statement to initialize the index i is 0, the loop condition is less than the array length of the index, and the step operation increments the index I, the loop body prints the array elements.

In for, each statement can be empty, that is to say:

for (;;) {}

Is valid, this is a dead loop, has been idling, and while (true) {} The effect is the same. Some statements can be omitted, but semicolons are not saved. Such as:

Int[] arr = {1,2,3,4};  int i=0;  for (; i<arr.length;i++) {System.out.println (arr[i]);}    

The index variable is initialized outside, so the initialization statement can be empty.

Foreach

The syntax for foreach is shown in the following code:

Int[] arr = {1,2,3,4};  for (int element:arr) {    System.out.println (element);}   

foreach uses a colon: the colon is preceded by each element in the loop, including the data type and the variable name, followed by the array or collection to be traversed (for a collection of our subsequent articles), and each loop element is automatically updated. The foreach syntax is more concise for situations where you do not need to use an indexed variable, just a simple traversal.

Loop Control-Break

In the loop, the loop condition is used as the basis for whether or not to end, but sometimes the loop can be terminated prematurely based on other conditions. For example, when looking for an element in an array, the loop condition may be the end of the array, but if you find an element, you might want to end the loop prematurely, and you can use break.

We mentioned a break when we introduced switch, which was used to jump out of switch. Break can also be used in the loop body of loops, which has the same meaning as in switch and is used to jump out of a loop and start executing the statements following the loop. To look up an element in an array as an example, the code might be:

finds the element in the array // the element to find int i = 0;  for (; i<arr.length;i++if (arr[i]==break;}} if (i!=arr.length) {System.out.println ("found");} else{System.out.println ("not Found");}           

If it is found, it will call break, and break will jump out of the loop after execution, and no longer execute the i++ statement, so even if the last element matches, I is also less than arr.length, and if not found, I will eventually become arr.length, so I can determine whether I am equal to Arr.length to find out.

In the above code, it is also possible to put a check on whether a finding is found in a loop condition, but in general, using break might make the code clearer.

Cyclic Control-Continue

In the loop, some code may not need to be executed every time the loop, at this point, you can use the Continue statement, the Continue statement skips the remainder of the loop body code, and then perform the stepping operation. Let's look at an example where the following code counts the number of an element in an array:

finds the element in the array // element to find int count = 0;  for (int i=0;i<arr.length;i++if (arr[i]!=continue;} count++;} System.out.println ("Found count" +count);          

The above code counts the number of elements in the array that are equal to Tosearch, and if the value is not equal to Tosearch, skip the remaining loop code and execute the i++. The above code can also be used without continue, using the opposite if judgment can also get the same result, this is only a matter of personal preference, if similar to skip the situation is more, the use of continue may be more concise.

Loop nesting

Like if, loops can also be nested, opening another loop in a loop body. In a nested loop, the break statement only jumps out of the loop, and the continue is the same.

Cycle Nature

As with if, the inner loop is also implemented by conditional transfer and unconditional transfer instructions. For example, the following code:

Int[] arr = {1,2,3,4};  for (int i=0;i<arr.length;i++) {    System.out.println (arr[i]);}   

The corresponding jump process may be:

1. int[] arr = {1,2,3,4};
2. int i=0;
3. conditional Jump: If i>=arr.length, jump to line 7th
4. SYSTEM.OUT.PRINTLN (Arr[i]);
5. i++
6. Jump to the 3rd line unconditionally
7. Other Codes

In the IF, the jump will only jump back, and for Will jump forward, the 6th line is the unconditional jump instruction, jump to the previous line 3rd. The Break/continue statement will also be converted to a jump instruction.

Circular Summary

The syntax of the loop is also relatively simple in general, and beginners need to be aware of the for execution process, as well as the meaning of break and continue.

Although loops appear to be just repeating a few similar operations, but it is actually a computer program to solve the problem of a basic way of thinking, with the cycle (of course, there are other), computer programs can play a powerful ability, such as batch conversion data, find filtering data, statistical summary and so on.

Using basic data types, arrays, basic operations, plus conditions and loops, you can actually write a lot of programs, but using the basic types and putting the code together is difficult to understand, especially when the logic of the program is more complex.

The basic strategy for solving complex problems is to divide and conquer, decompose complex problems into less complex sub-problems, and then decompose sub-problems into smaller sub-problems ... The program consists of data and instructions, the large program can be broken down into small programs, small programs then decomposed into smaller programs. How do you represent subroutines, and how do you coordinate between subroutines?

Logic of the computer program (10)-Powerful cycle "turn"

Related Article

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.