© Doug Winnie 2021
D. WinnieEssential Java for AP CompScihttps://doi.org/10.1007/978-1-4842-6183-5_39

39. The do/while Loop

Doug Winnie1  
(1)
Mission Hills, KS, USA
 

The while loop runs if the condition at the top is true, but you might have a case when you need to run the code in the loop at least once, or you need to test the condition at the end of the loop.

The solution to this is the do...while loop. The do...while loop is identical to the while loop, except the condition statement is tested at the end. As a result, the loop will always run at least one time, and if the condition at the end of the loop is true, the loop will repeat. If the condition at the end is false, it will not repeat the loop, and the flow of the program will continue with the next statement.

Creating a do…while Loop

A do...while loop starts with the do clause and then a code block, defined by braces. After the code block, the while clause is added with the conditional statement:
int a = 5;
do {
System.out.println(a);
a--;
} while (a > 0);

In this example, the loop will run five times, starting with the value 5 and then decrement that by 1 with each execution of the loop.

Run at Least Once

In the following example, the loop will run once, because the condition is tested at the end:
boolean loop = false;
do {
System.out.println("Run this loop!");
} while (loop);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.118.99