Loop execution flow

 

In the diagram above you can see the basic normal flow of a loop and how it executes. As you will find later, there are more than one types of loops, but all of them they work the same way. 

At the beginning there is an initial state when the loop starts (for example we set a variable x = 1),

then always we check if a condition evaluates to true (in this case the condition is x < 100),

if this is true, then we execute some code we define.

After the execution of the code, we may update the value of x to 2.

Then we check the condition again ( x < 100 which is still true), execute the same code as before.

We update and continue these steps until the condition that is specified evaluates to false, this causes our loop to break and exit. (stop being executed in other words). 

The while loop

 

There are more than one ways to execute a repeated code. While loop is one of the commonest. The syntax can be found above in the picture, the first step is instantiating a variable and giving a specific value. Most of the times this is going to be a number but as we will see later in the course this is not mandatory (many times you will find out it can be boolean etc).

Inside the while parenthesis follows a condition (that returns a boolean value always). While this condition is true, the code inside the following curly braces will be executed.

Last but not least, we need to update the value of the "Counter" variable. This is very important in order to avoid loop infinity. Avoid creating a loop whose condition ALWAYS evaluate to true, and thus runs forever.

Once the body of the loop is over, the value has been updated and then the condition is checked again in order to decide if we will execute the body of the loop once again or we will exit the loop!

Already confused let's see a practical example!