Appearance
Do While Loop
In Java, the while
loop first determines the loop condition and then executes the loop. Another type of do while
loop executes the loop first and then judges the conditions. When the conditions are met, the loop continues and exits when the conditions are not met. Its usage is:
java
do {
//Execute loop statement
} while (condition);
It can be seen that do while loop will loop at least once.
Let’s rewrite the sum of 1 to 100 using do while loop:
java
// do-while
public class Main {
public static void main(String[] args) {
int sum = 0;
int n = 1;
do {
sum = sum + n;
n ++;
} while (n <= 100);
System.out.println(sum);
}
}
When using do while
loops, you must also pay attention to the judgment of loop conditions.
Practise
Use do while loop to calculate the sum from m to n .
java
// do while
public class Main {
public static void main(String[] args) {
int sum = 0;
int m = 20;
int n = 100;
// Use do while to calculate M+...+N:
do {
} while (false);
System.out.println(sum);
}
}
Summary
do while
first executes the loop and then determines the condition;
do while
loop will be executed at least once.