SoFunction
Updated on 2025-03-08

Give an example to explain the use of do-while statement in Java

Before learning the do/while statement, be clear about how the while statement works. The while statement first makes conditional judgments, and then executes the loop body in curly braces.
The difference between the do/while statement and the while statement is that it first executes the loop body in the braces, and then judges the condition. If the condition is not met, the loop body will not be executed next time. That is to say, the loop body in the braces is executed before judging the conditions.
Example: Calculate the result of 1+2+3+4...+100.

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

When do-while declares, it will cycle 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 {
   (i);
   i++;
  } while (i < 3);
 }
}

The following do-while shows that at least the block code will be executed, even if the initial value is once used for the test expression [j]. < 3 is calculated incorrectly.
 

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

Use do while to sum

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);
  ("sum = " + sum);
 }
}

Let’s summarize the differences between three cycles:
Loop first judges -> decide whether to execute the loop
-while is to execute the loop first->judgment whether->and then continue to see if
Loop: First execute the initialization loop; then execute the judgment, call first, then execute the content of the loop body, print out the variable value; then execute the parameter modification part. It means to judge first and then execute.