This article completely copies the contents of the Introduction to Programming (Java) 3.2.4 Loop statement, in addition to the explanatory text in the. Please read and compare other programming materials.
I know that if I were a beginner,the introduction to Programming (Java) is not suitable for self-study . Students are advised to read, be sure to choose one of the other books at the same time, or the Internet . , because too general or simple content, or I do not want to stay in the book occupies the space of things, are omitted. After all, the content of the general description on the web is a lot.
In modern times, Chaplin shows how depressing it is for workers on the assembly line to repeatedly perform the same action under high intensity. However , the loop/iteration (loop/iteration) repeats one or more operations that the computer is good at. One of the most important aspects of learning programming is to overcome the discomfort of human being to the cyclic structure and to master the cyclic structure thoroughly. " for starters, loops are a small hurdle ."
1. Loop basis: While statement
A loop/Iteration statement executes a block of code repeatedly based on the value of an expression. There are 3 forms of a looping statement: while, Do-while, and for statements. The most basic loop statement is the while statement.
Routine 3-5 the most original loop statement package Semantics.statement;public class whiledemo{ /** Print [0,10) * /public static void Loopprint ( ) { int n = 0; while (n < ten) System.out.println (n++); } /** the integer and of the [0,n]. */public static void sum (int n) { int total=0;//Save result while (n > 0) Total + = n--; SYSTEM.OUT.PRINTLN (total);} }
The while statement has the same structure as the single-radio if statement , and if the if is changed to a while it becomes a while statement. Its syntax is:
while (B-E) {
Statement (s) T
}
The semantics are: encountered the keyword while, to find the value of B-E. When/As long as (while) B-E is true, the subsequent block of code-the loop body is executed, and the B-E value is evaluated again after the loop body executes, until B-E is false to skip the block of code.
The while statement is like a single-choice if statement that can be executed repeatedly. The Boolean expression b-e is referred to here as a loop condition, and if (true) or while (true) is encountered, the code block of the radio if is executed only once, while the while statement may be executed forever. effectively terminating the cycle is the key to mastering the cycle.
2 while ((i = In.read ())!=-1). When reading a file, once the data read is-1, indicating that the file ends, and thus the loop ends.
Loops are monitored by a sentinel, called Sentinel end mode. Sentinel (Sentinel) is a special value that causes the loop to end , the user enters the value, or the value is calculated to cause the loop to end. Sentinel End mode is usually not able to determine the number of cycles in advance. When reading a file, 1 is the Sentinel. When writing a loop statement for the Sentinel end pattern, pay special attention to ensuring that the loop effectively ends. If an infinite loop appears in the Bulej, right-click the JVM's working status bar and restart the JVM (ctrl+shift+r).
Another typical application of Sentinel end mode is to define a special string, such as "886", to terminate the program when the keyboard input is accepted.
2 for (int i =0; i<array.length;i++). For the processing of an array of arrays, the length of the parameter array is the loop end condition.
N-Times End modeis another loop-over pattern, which means that the loop executes a predictable number of times, and the program runs automatically until it ends without relying on external conditions. For example, the sum of the individual numbers of a positive integer is obtained. Any positive number, such as 12345,12345/10, is 1234, with each loop executing
N/=10Then n becomes 1234, 123, 12, 1, 0. Thus the conditions of the loop end are n! = 0. "Note that a large number of programs on integers use n/=10 and N%10"
Routine 3-6 N-times End mode public static void DSum (int n) { int total=0; while (n! = 0) {Total + = n%10; n/=10; } SYSTEM.OUT.PRINTLN (total); }
The while (n!=0) in the program is usually expressed as while (n> 0), the effect is the same.
Assuming that the loop condition is changed to while (N> =0), when n becomes 0, the computer will execute the loop body over and over and over and over again, each time n equals 0. This condition is known as the current infinite loop (infinite loop).
In an example of an integer of [0,n] and the sum of each number of numbers that seek a positive integer, there is an expression that alters the value of n (to change the value of B-E), such as n++, which is called a count expression (counting expression). It makes the loop tend to end.
| Exercise 3-1 .: The loop statement in routine 3-5 can be written as a singleton such as while (n > 0) Total + = n--; What is the count expression in this sentence? Can I use--n? |
| Exercise 3-2: Programming. Semantics.statement. Whiledemo adds a method to calculate the factorial of n (factorial). /** * To find the factorial of N. Mathematical definition of factorial: n>0,n!= 1*2*...*n. * @param n natural number n. (n>0) * @return the factorial of N. If n<1, return to 0; if n>=13, pay attention to overflow. */ public static int factorial (int n) |
| Exercise 3-3: Programming calculation [1,n] odd-numbered and. Tip: The count expression is an assignment expression n+=2. |
| Exercise 3-4: Programming validation 3x+1 issues. Any natural number x is calculated according to the following rules, resulting in 1. Rule: If the number is even, divide by 2, or if it is odd, multiply by 3 and add 1. The resulting number is repeated in accordance with this rule and can eventually be 1. This problem is known as the 3x+1 problem, the Syracuse conjecture, the Corraze (Collatz) conjecture, or the angular valley conjecture. Hint: The loop test expression is x!=1, or another power of 2 such as x!=2. |
If B-E is first executed 0 times for the loop body of the False,while statement. In order to ensure that the loop body executes at least once, the Do-while statement can be used:
do{
statements;
} while (BE);
Note: The Do-while statement requires a semicolon.
2. For statement
The most common loop statement is the FOR statement. It sets the 3 expressions associated with the loop- initialization expressions, cyclic test expressions, and Count expressions -in a () after. This 3-expression for loop (three-expression for loops) is used in almost all languages since the C language.
for ([Forinit]; [B-E]; [Forupdate]) {
< cycle body >
}
2 test expression B-e, as with the B-E loop test in a while statement, executes the subsequent loop body as long as its value is true. If the loop test expression is omitted, the default is true, while the while statement cannot be omitted, at least while (true) {}.
2 initializes the expression Forinit, which mainly indicates how the index variable (index variable) used in the loop is initialized. In the case of the for (int i=0;i<10; i++), the index variable i is initialized to 0. The index variable represents the round of the loop, which participates in the loop body calculation, reflecting the difference in each cycle.
The 2 count expression, commonly called step, represents the magnitude and direction of the step, specifying how the cyclic index variable changes after each round, such as i++, I-=2, and so on.
The For statement is executed as shown in procedure 3-4. Slightly One of the few flowcharts that is rare in this book "
Reverting the For statement to the form of a while statement helps familiarize yourself with the execution flow of the for statement.
for (init; test; step) {statements;} Equivalent to the following while statement:
Init
while (test) {
statements;
Step
}
For programming beginners, it is not difficult to understand the for statement, the key is to repeat and a lot of practice. After all, people are not very good at and do not like to do things in a loop. In order to take advantage of the computer's hard-to-do, we need to write various circular statements.
Routine 3-7 prime package semantics.statement;import static Java.lang. math.*;p ublic class prime{ /** * Determines whether the parameter n is a prime number */Public static Boolean isprime (int n) { if (n==1) return false; for (int j=2; j< math.sqrt (n+1); j + +) { if (n%j==0) return false; } return true; }}
3. Variants of the FOR statement
3-The For loop of the expression, each of which is optional (can be omitted).
such as: for (;;) break;//
The syntax requirement for A For loop is: Forinit can be 1) local variable declaration, 2) An expression group that can form an expression statement. Instead, forupdate can be an expression group. Expression groups are multiple expression statements separated by a delimiter comma. Expression groups are used only for a For loop (while these constituent components do not exist in the while). You can therefore write the for statement as follows:
intx=10,y=0;
For (System.out.println (x), y++; x>y; x=x-2,y=y*2,system.out.println (y));
Compile no problem, BlueJ will appear red warning on class diagram: This class cannotcurrently is parsed, but does not affect the operation of the code.
To keep the code readable, you need to constrain yourself from using method calls, self-increment statements in Forinit, and only local variable declarations or assignment statements; in Forupdate, only self-increment and assignment statements are used.
If the loop is controlled by two variables that interact with each other, a comma is more reasonable.
for (int i=0,j=10; i<j; i++,j--) {
SYSTEM.OUT.PRINTLN (i + "" +j);
}
In Java code written by some professional programmers, variants of various looping statements, including empty loop bodies, commas, and self-increment or decrement, are used in each expression. For example, the intermediate values of I and J can be as follows:
int i=0;
for (int j=10; ++i <--j;); Empty statement
System.out.println ("median is" +i);
Exercise 3-1: Use the For statement for the while part of the exercises. |
Exercise 3-2: Simulates the standard while statement with a for (; Loop test expression;) {loop body}. Describes the advantage of a for statement over while. |
Exercise 3-3: Describes the possible problems with using floating-point numbers for cyclic condition testing in a looping statement. |
Exercise 3-4: Use progression to approximate values. Known "Formula" Programming e (Double x), use the Do-while statement to calculate the approximate value of the e^x. |
Exercise 3-5: Programming Fibonacci (), using the while statement and the for statement to output the first 10 items of the Fibonacci sequence, respectively. Known "Formula" |
4. Nested loop structure
Looping statements appear in various loops and can form nested loop structures. It is interesting to look at [11th chapter sort], which has a lot of examples. Here Print 99 multiplication table, total 9 rows 9 columns, outer loop index I control row, Inner Loop index J control column.
Routine 3-8 99 multiplication table package Semantics.statement;import static tips. print.*;p ublic class fordemo{ /** print out 99 multiplication table */public static void Mul99 () {for (int i=1; i<10; i++) { fo R (int j=1; j<=i; j + +)///j<=i triangle, j<10 rectangle System.out.printf ("%d*%d=%2d", I, J, I * j); PLN (); } } public static void Table99 () {for (int i=1,j=1; i<10; j = (j==9)? ( ++i):(j+1) { p (i+ "*" +j+ "=" +i*j+ (j==9? ' \ n ': ');}}}
The output of call mul99 () is:
1*1= 1
2*1= 2 2*2= 4
3*1= 3 3*2= 6 3*3= 9
4*1= 4 4*2= 8 4*3=12 4*4=16
......
The output of call Table99 () is:
1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9
2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=162*9=18
......
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Introduction to Programming (Java) 3.2.4 Looping statements