While Loop

0 rebbecaclemes38 December 8, 2020

In the last tutorials, We have discussed for loop. In these tutorials, We will discuss the while loop in this tutorials. As we know, Loops are the block of statement that executes repeatedly until the condition is false.

While Loop

The syntax of while loop is:

while(test condition)
{
    //body of loop
}

The test condition evaluates and if the condition is true, then the body of the loop executes. After execution of the body once, the test-condition is again evaluating and if it is true, the body executes once again. This process repeats execution of the body continues until the test-condition finally becomes false and the control transfers out of the loop. On exit, the program continues with the statement immediately after the body of the loop.

While loop Flowchart
While loop Flowchart

Note: When the frequency of repetition is known as advance, We use the for loop and when it is not known, the while loop is suitable.

Let’s loop upon one example to clear the concept of a whileloop.

<?php

$i=1;
while($i <= 10)
{
    echo "The value of i = $i";
    $i++;
}

?>

The output of the above program is:

The value of i = 1
The value of i = 2
The value of i = 3
The value of i = 4
The value of i = 5
The value of i = 6
The value of i = 7
The value of i = 8
The value of i = 9
The value of i = 10

Do While Loop

The syntax of do while loop is:

do
{
   statement;
}while(test condition);

In the do while loop, the body of the loop is executed first without testing condition. At the end of the loop, the test condition in the while statement evaluates. If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop terminates and the control goes to the statement that appears immediately after the while statement.

Do While Loop Flowchart
Do While Loop Flowchart

Le’ts look one example:

<?php

$i = 1;
do{
    echo "The value of i = $i";
    $i++;
}while($i <= 10);

?>

The output of the above program is:

The value of i = 1
The value of i = 2
The value of i = 3
The value of i = 4
The value of i = 5
The value of i = 6
The value of i = 7
The value of i = 8
The value of i = 9
The value of i = 10

Difference between While and Do While Loop:

While LoopDo While Loop
The statement executes after the condition is checked.The statement executes at least once, then after the condition is checked.
The statement executes zero times if the condition is fast at first.At least once, the Statement executes.
There is no semi-column at the end of the while loop.The is a semi-column at the end of the while loop.
If there is a simple statement, Brackets are not required.Brackets are required for all conditions.
While loop is entry controlled loop.Do while loop is exit controlled loop.