Do-while Loop
Get acquainted with the do-while loop and its basic syntax in this lesson.
We'll cover the following
What is a do-while
loop?
The do…while loop is nearly identical to the while
loop, but instead of checking the conditional statement before the loop starts, the do…while loop checks the conditional statement after the first run, before moving onto another iteration.
The syntax is as follows:
while
vs. do-while
loop
The while
loop runs the code inside it if and only if the condition inside the parenthesis is true. The do...while
, however, runs the loop at least once before checking the condition.
Note: The
do...while
loop is still haunted by infinite loops, so exercise the same caution with thedo...while
loop as you would with thewhile
loop. Its usefulness is more limited than thewhile
loop, so use this only when necessary.
Example
Below is an example showing how to implement the do-while
loop in Perl.
$number=5;do{print "Value of number is: $number\n";$number++;} while($number<=9); # the contition is being checked after the first run
Explanation
The illustration below will help you better understand the logic of the above code.
When is a do-while
loop used?
A do-while loop is used where your loop should execute at least once.
For example, let’s consider a scenario where we want to take an integer input from the user until the user has entered a positive number. In this case, we may use a do-while as we have to run loop at least once because we want input from user at least once. This loop will continue running until the user enters a positive number.