When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Myclass { public static void main(String[] args) { int num = 9; boolean divisibleBy7 = false; do { System.out.println(num); if (num % 7 == 0) divisibleBy7 = true; num--; } while (divisibleBy7 == false); } } |
Output
1 2 3 4 5 |
9 8 7 |