Loops allow us to run the same block of code multiple times automatically in BHP.
We have four different types of loop statements.
The while loop the do while loop before loop in the for each loop let's start with an example of the
while loop in this example.
We have a variable X with its value set to 1 we've then created a while loop that will loop over and
over again as long as the value of x is less than 10
using a post increment operator inside a while loop.
We can keep incrementing the value of X until it reaches its maximum limit.
In this situation which is 9 since x is initially set to 1 the first time the loop runs the value of
x will be 1.
The second time it runs it will incremented 2.
It will continue to increment until it reaches a value less than 10.
So 9 we can see this in our web browser we can see that the loop runs over and over again and each time
it outputs the statement the number is and then the value of the loop at that instant
if we change 10 to 20 we'll see that the loop now runs 19 times
if we change the value of x to 5
we can see that X will start incrementing at 5
will change the value here back to 10 but now what if we change the value of X to a value greater than
10.
Say you live in
we can see in our web browser that there is now no output the Y loop checks to make sure a specified
condition is true first before executing the loop so it checks to see if x is less than 10 first and
if it is it will go ahead with the loop if not it will not execute the loop.
Now let's take a look at the do while loop this type of loop is different in that it will execute a
block of code once and then it will check to see if the condition is true.
From that point it will repeat the loop only if the condition is true in this example.
We have a variable X set to the value of six next.
We've created our do while loop we specify the action which is to echo the value of x and once the value
is output it we then have an increment operator that increases the value of X by 1 after the increment
operator.
We have our while statement and then the condition the condition states that this loop should only be
repeated if x is less than or equal to 5 in this case it's not.
So the loop will not run again.
Since X is actually equal to 6.
Now we can see in our web browser that the loop did execute once but there will be no further output
because the loop will not XY will not run again if we were to reduce the value of x to say 2.
Now the while loop will run because the value of x is less than or equal to 5 so it will continue to
run until that condition is no longer met and that is the difference between a while and a do while
loop.