Java looping structure-for, while and Do...while

Source: Internet
Author: User

Java looping structure-for, while and Do...while

The sequential structure of a program statement can only be executed once. If you want the same operation to execute multiple times, you need to use the loop structure.

There are three main loop structures in Java:

    • While loop
    • Do...while Cycle
    • for Loop

An enhanced for loop that is primarily used in arrays is introduced in Java5.

While loop

While is the most basic loop, its structure is:

while// loop content}  

As long as the Boolean expression is true, the loop experience continues.

Instance Test.java file code:
 Public class Test {   publicstaticvoid  main (String args[]) {      int x = Ten;        while (x < ) {         System.out.print ("Value of x:" + x);         X+ +;         System.out.print ("\ n")      ;    }}

The results of the above example compilation run as follows:

Value of X:10-19

Do...while Cycle

For a while statement, you cannot enter a loop if the condition is not met. But sometimes we need to do it at least once, even if we don't meet the conditions.

The Do...while loop is similar to the while loop, but the Do...while loop executes at least once.

 Do {       // code statement }while (boolean expression);

Note: The Boolean expression is behind the loop body, so the statement block is executed before the Boolean expression is instrumented. If the value of the Boolean expression is true, the statement block executes until the value of the Boolean expression is false.

Instance Test.java file code:
 Public class Test {   publicstaticvoid  main (String args[]) {      int x = ten;         Do {         System.out.print ("Value of x:" + x);         X+ +;         System.out.print ("\ n");      }  while (x < );}   }

The results of the above example compilation run as follows:

Value of X:10-19

For loop

Although all loop structures can be represented by while or Do...while, Java provides another kind of statement--for Loop, making some loop structures easier.

The number of times the For loop executes is determined before execution. The syntax format is as follows:

for// code statement}  

There are several explanations for the For loop:

    • The initialization step is performed first. You can declare a type, but you can initialize one or more loop control variables, or you can be an empty statement.
    • Then, the value of the Boolean expression is detected. If true, the loop body is executed. If False, the loop terminates, starting execution of the statement following the loop body.
    • After the loop is executed, the loop control variable is updated.
    • Re-detects the Boolean expression. The loop executes the above procedure.
Instance Test.java file code:
 Public class Test {   publicstaticvoid  main (String args[]) {       for ( int x = 10; x < 20; x = x+1) {         System.out.print ("Value of x:" + x);         System.out.print ("\ n")      ;    }}

The results of the above example compilation run as follows:

Value of X:10-19

Java Enhanced for loop

JAVA5 introduces an enhanced for loop that is primarily used for arrays.

The Java enhanced for loop syntax format is as follows:

for// code sentence}  

declaration statement: declares a new local variable that must have a type that matches the type of the array element. Its scope is scoped to the Loop statement block, whose value is equal to the value of the array element at this time.

expression: The expression is the name of the array to access, or is the method that returns the value to the group.

Instance Test.java file code:
 Public classTest { Public Static voidMain (String args[]) {int[] numbers = {10, 20, 30, 40, 50};  for(intx:numbers)         {System.out.print (x); System.out.print (","); } System.out.print ("\ n"); String [] Names={"James", "Larry", "Tom", "Lacy"};  for(String name:names) {System.out.print (name); System.out.print (","); }   }}

The results of the above example compilation run as follows:

10,20,30,40,50, James,larry,tom,lacy,

The Break keyword

Break is used primarily in loop statements or switch statements to jump out of the entire block of statements.

Break jumps out of the innermost loop, and continues execution of the statement below the loop.

Grammar

The use of break is simple, which is a statement in the loop structure:

break;

Instance Test.java file code:
 Public classTest { Public Static voidMain (String args[]) {int[] numbers = {10, 20, 30, 40, 50};  for(intx:numbers) {         //x equals 30 o'clock jumps out of the loop         if(x = = 30 ) {             Break;         } System.out.print (x); System.out.print ("\ n"); }   }}

The results of the above example compilation run as follows:

1020

Continue keywords

The Continue is suitable for any loop control structure. The function is to let the program jump immediately to the next iteration of the loop.

In the For loop, the continue statement causes the program to jump immediately to the UPDATE statement.

In the while or Do...while loop, the program immediately jumps to the judgment statement of the Boolean expression.

Grammar

Continue is a simple statement in the loop body:

continue;

Instance Test.java file code:
 Public class Test {   publicstaticvoid  main (String args[]) {      int [] Numbers = {Ten, +, +, +, +};         for (int  x:numbers) {         if(x = = ) {        continue; 
    }         System.out.print (x);         System.out.print ("\ n")      ;    }}

The results of the above example compilation run as follows:

10204050
List of Notes
  1. For Nested loop instances:

     for (int i=1; i<=3; i++) {    for (int n=1; n<=3; n++) {        //  Output results ....         System.out.println ("i =" + i + ", n =" + n);    }}

    The first for: set an integer variable i, whose initial value is 1, whether I is less than or equal to 3, and if so, I will increase by 1.

    The second for: determines an integer variable n, whose initial value is 1, whether n is less than or equal to 3, and if so, n increases by 1.

  2. For loop nesting: example of printing a 99 multiplication table

     Public class Test {    publicstaticvoid  main (String args[]) {        for ( int i=1;i<=9;i++) {            for (int j=1;j<=i;j++) {                System.out.print (J+ "*" +i+ "=" +i*j+ "\ T");            }            System.out.println ();     }}}

    First For loop: represents the number of rows. Set an integer variable i, whose initial value is 1, whether I is less than or equal to 9, and if so, I will increase by 1.

    Second For loop: Represents the number of columns. Set an integer variable J, whose initial value is 1, whether J is less than or equal to I, and if so, j increases by 1.

Java Looping structure-for, while and 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.