Before learning the do/while statement, first understand how the while statement works. The while statement first performs conditional judgment and then executes the loop body within the curly braces.
The difference between the do/while statement and the while statement is that it first executes the loop body within the curly braces, and then judges the condition. If the condition is not met, the loop body will not be executed next time. In other words, the loop body within the curly braces has been executed before the condition is judged.
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);System.out.println(result);}}
When do-while is declared, it will loop 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 the do block of code will be executed, even once the initial value is used to test the expression [j]. . < 3 evaluates to errors.
public class mainclass { public static void main(string[] args) { int j = 4; do { system.out.println(j); j++; } while (j < 3); }}
Use do while to find the 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); system. out.println("sum = " + sum); }}
Summarize the differences between the three types of loops:
1. While loop first judges -> decides whether to execute the loop
2. do-while is to execute the loop first -> determine whether -> then continue to see whether
3. for loop: first execute the initialization loop; then execute the judgment, first call, then execute the content of the loop body, and print out the variable value; then execute the parameter modification part. Just judge first and then execute.