Do-while loop
Defination:
In a do-while loop, firstly, the code is executed once.
After that, if the condition is true, the code inside the curly braces executes, followed by the increment or decrement.
Then, the loop rechecks the condition.
If the condition is false, the loop exits from the curly braces.
Now you will clearly understand the code logic with the help of the flowchart.
Do-while Loop Flowchart
First step: → You will write the program
|
Second step: → First the code will run one time (without checking condition)
|
After that, you will check the condition (true/false)
If you find the condition "True", then
|
Execute Code
|
Go back and check the condition again
If the condition is "False", then
|
Stop the loop
|
End the program
Syntax:
do {
// The code is written here and executed once.
// After that, the condition is checked.
} while (condition);
Example:
Write a PHP program to print the even numbers from 2 to 10 using a for loop.
<?php
$i = 2;
do {
echo " $i<br>";
$i += 2;
} while ($i <= 10);
?>
Output:
2 4 6 8 10
