Illustrate the use of the do while statement in Java

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

Before you learn about the do/while statement, understand how the while statement works. A while statement is a conditional judgment before the loop body in braces is executed.
The do/while statement differs from the while statement in that it executes the body of the loop inside the braces and then determines the condition. If the condition is not satisfied, the body of the loop will not be executed next time. That is, the body of the loop in braces is executed before the condition is determined.
Example: calculate 1+2+3+4... Plus 100.


public class control5{
public static void main(String[] args){
int a=1,result=0;
do{
result+=a++;
}while(a<=100);
System.out.println(result);
}
}

When a do-while statement is declared, it loops at least once.

Its syntax is as follows:


do {
  statement (s)
} while (booleanexpression);

Simple example


public class mainclass {
 public static void main(string[] args) {
  int i = 0;
  do {
   system.out.println(i);
   i++;
  } while (i < 3);
 }
}

The following do-while indicates that at least a block of code will be executed, even once the initial value is used to test the expression [j].. < 3. Miscalculated.
 


public class mainclass {
 public static void main(string[] args) {
  int j = 4;
  do {
    system.out.println(j);
    j++;
  } while (j < 3);
 }
}

Sum using do while


public class mainclass {
 public static void main(string[] args) {
  int limit = 20;
  int sum = 0;
  int i = 1;
  do {
   sum += i;
   i++;
  } while (i <= limit);
  system.out.println("sum = " + sum);
 }
}

Summarize the differences between the three cycles:
1. While loop judge first -> Decide whether to execute the loop
Do -while is the first to execute the loop -> Judge whether -> Let's see if we can
3. For loop: execute the initialization loop first; Then execute the judgment, first call, then execute the contents of the loop body, the variable value is printed; The parameter modification part is then performed. Judge before you execute.


Related articles: