More on do in Java... The use of a while loop statement

  • 2020-04-01 04:18:45
  • OfStack

For the while statement, if the condition is not met, you cannot enter the loop. But sometimes we need to do it at least once, if not at all.
The do... While loop is similar to while loop except that do... The while loop executes at least once.


do {
    //The code statement
}while( Boolean expression );

The do.. The while loop statement is also known as the posttest loop statement, and its loop repeats, also using a condition to control whether or not the statement is repeated. Unlike the while loop, it executes the loop once before deciding whether to continue. For example, to calculate the sum of all integers between 1 and 100, you can also use do... While loop statement implementation. The specific code is as follows:


int sum=0;
int i=1;
do{
sum+=i;
i++;
} while (i<=100);
System.out.println("1 to 100 The sum of all integers is : "+sum);

The do... The while loop executes by executing the body of the loop once, then judging the conditional expression, and if the conditional expression is true, it continues, or the loop is broken. That is to say, do... The loop body in the while loop statement is executed at least once.

Note: the Boolean expression follows the body of the loop, so the statement block is executed before the Boolean expression is detected. If the Boolean expression is true, the statement block executes until the Boolean expression is false.
The instance


public class Test {

  public static void main(String args[]){
   int x = 10;

   do{
     System.out.print("value of x : " + x );
     x++;
     System.out.print("n");
   }while( x < 20 );
  }
}

The compilation and operation results of the above examples are as follows:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19


Related articles: