Introduction to Programming (Java) & #183; 3.2.4 Loop Statement "

Source: Internet
Author: User

This article completely copies the contents of the Introduction to Programming (Java) 3.2.4 Loop statement. In addition to the description text in the. Please read and compare other programming materials.

I know. Suppose I am a person who has just started to learn,"Introduction to Programming (Java)" is very unsuitable for self-study . Students are advised to read, be sure to choose one of the other books at the same time to see, or surf 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 relevant general descriptive narrative on the web. Lots and lots.

Chaplin in the modern times. Shows how frustrating it is for workers on the assembly line to repeat the same action at high intensity. However , a loop/iteration (loop/iteration) that repeats one or more operations is the computer's forte. One of the most important aspects of learning programming is to overcome the discomfort of the human cycle structure and to master the cycle structure thoroughly. " for those who have just started learning, the cycle is a small hurdle ."

1. Loop basis: While statement

A loop/Iteration statement runs 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 important 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 and the single-radio if statement structure are the same. Changing if to while is a while statement.

Its syntax is:

while (B-E) {

Statement (s) T


The semantics are: encounter Keywordwhile, seek b-e value. When/Just (while) b-e is true, the subsequent code block-the loop body -is run. After the loop body runs, the value of B-E is again evaluated. Blocks of code are skipped until B-E is false.

The while statement is like a single-choice if statement that can be run repeatedly.

The Boolean expression b-e is referred to here as the loop condition. If you encounter if (true) or while (true), the code block for the radio if is run only once, while the while statement may run forever.

effectively terminating the cycle is the key to mastering the cycle.

2 while ((i = ())!=-1). When reading a file, once the data read is-1, indicating that the file ends, and thus the loop ends.

The loop is 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 not usually able to determine the number of cycles in advance.

When the file is read. -1 for Sentinel.

When writing loop statements for Sentinel end mode, pay special attention to ensuring that loops can end effectively. Assuming an infinite loop appears in the Bulej, right-click the JVM's working status bar and restart the JVM (ctrl+shift+r).

A typical application for Sentinel end mode is when you accept keyboard input. Defining a special string, such as "886", means terminating the program.

2 for (int i =0; i<array.length;i++).

The processing of an array of arrays, the length of the array is the loop end condition.

N-Times End modeis another loop-over pattern, which means that the loop will run as many times as you can predict. The program will run its own initiative until the end without relying on external conditions. Another example is to find the sum of the numbers of a positive integer.

Any positive number, such as 12345. 12345/10 is 1234. As each loop runs n/=10 then n becomes 1234, 123, 12, 1, 0. Thus the conditions of the loop end are n! = 0. "Note that a large number of programs about 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 same effect.

If the loop condition is changed to while (N> =0), when n becomes 0, the computer will run the loop body over and over and over and over again, each time n equals 0. Such a situation is known as an infinite loop (infinite loop).

In the example of an integer sum of [0,n] and the sum of the individual numbers of 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 (n > 0) Total + = n--;

What is the count expression in this sentence? Can you use--n?

Exercise 3-2: Programming. Semantics.statement. The Whiledemo method is added to calculate the factorial of n (factorial).


* 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. Suppose N<1. Return is 0; Suppose n>=13, notice overflow.


public static int factorial (int n)

Exercise 3-3: Programming computes [1,n] between odd-numbered and. Tip: The count expression is an assignment expression n+=2.

Exercise 3-4: Programming validation 3x+1 issues. Calculate any natural number x according to the following rule, and you can finally get 1.

Rule: If number is even. Divide by 2, if it is odd. Then multiply by 3 and add 1.

The resulting number is repeated in accordance with this rule. Finally, we can get 1.

This problem is referred to as 3x+1 problem, Syracuse conjecture, Corraze (Collatz) conjecture or Angular valley conjecture.

Tip: The cyclic test expression is x!=1. or 2 of other powers such as x!=2.

Let's say that B-e runs 0 times for the loop body of the False,while statement at the start.

To ensure that the loop body runs at least once, the Do-while statement can be used:



} while (BE);

Note: The Do-while statement requires a semicolon.

2. For statement

The most frequently used loop statement is the FOR statement.

It sets the loop-related 3 expressions- initialization expressions, cyclic test expressions, and Count expressions -in the back of a (). The for loop of such a 3 expression (three-expression for loops) is almost all used in all languages since the C language.

for ([Forinit]; [B-E]; [Forupdate]) {

< cycle body >


2 Test expression B-e. Same as the B-E loop test in the while statement. If only the value is true, the subsequent loop body is run. If the cyclic test expression is omitted, the default is true. The while statement cannot be omitted. is at least while (true) {}.

2 initializes the expression Forinit, which mainly indicates how the index variable (index variable) used in the loop is initialized. such as for (int i=0;i<10; i++). The index variable i is initialized to 0. The index variable represents the round of the loop. It participates in the calculation of the loop body. reflect the different cycles of each round.

The 2 count expression is often called step, which indicates the magnitude and direction of the step. Specifies how cyclic index variables change after each round, such as i++, I-=2, and so on.

The For statement is seen by running flow 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 running flow of the for statement.

for (init; test; step) {statements;} Equivalent to the following while statement:


while (test) {




For those who have just started to learn, it is not difficult to understand the for statement, the key is the need 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 use the computer's hard-to-do, you need to write various circular statements.

Routine 3-7 prime package semantics.statement;import static Java.lang. math.*;p ublic class prime{    /**     * inferred that 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 an 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.

And forupdate can be an expression group. Expression groups are multiple expression statements that are cut by a delimiter comma.

Expression groups are used only for a For loop (these constituent components do not exist in while). You can therefore write a for statement such as the following:


For (System.out.println (x), y++; x>y; x=x-2,y=y*2,system.out.println (y));

Compile no problem, BlueJ will appear on the class diagram red warning: This class cannotcurrently is parsed, but does not affect the execution of the code.

In order to maintain the readability of the code, it is necessary to constrain itself from the usage invocation, self-increment statement in Forinit. Instead, only local variable declarations or assignment statements are used; in forupdate, only self-increment and assignment statements are used.

It is reasonable to use a comma if the loop is controlled by two variables that affect each other.

for (int i=0,j=10; i<j; i++,j--) {



In Java code written by some professional program apes, variants of the various looping statements appear, including empty loop bodies, commas, and self-increment or decrement for each expression. For example, I and J of the median, 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: Simulate the standard while statement with a for (; cyclic test expression;) {loop body}. Describes the advantage of a for statement over while.

Exercise 3-3: Describes the possible problems of using floating-point numbers in a looping statement to test for cyclic conditions.

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 (). Use the while statement and the for statement to output the first 10 items of the Fibonacci sequence, respectively. Known "Formula"

4. Nested loop structure

Cyclic statements are also present in various circulating bodies. can form nested loop structures.

Interested in being able to read [11th chapter Sort], there are a lot of examples.

The 99 multiplication table is printed here. 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


Introduction to Programming (Java) & #183; 3.2.4 Loop Statement "

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: 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.