A loop is a programming structure that repeats a series of instructions until a condition being met, loops can be very useful and can save you lots of time.
- A definite loop is a loop in which the number of times it is going to execute is known in advance before entering the loop. The number of iterations it is going to repeat will be typically provided through an integer variable. In general, for loops are considered to be definite loops.
- In an indefinite loop, the number of times it is going to execute is not known in advance. Usually, an indefinite loop is going to be executed until some condition is satisfied. While loops and do-while loops are commonly used to implement indefinite loops. Even though there is no specific reason for not using for loops for constructing indefinite loops, indefinite loops could be organized using while loops.
In Dart there are three types of loops: for, while, and do…while. Let’s take a look at each one of them.
A for loop will run statements a specific number of times. For example, let’s say you have 20 products that you sell with 400 dollars. And you want to update each product and add a discount of 20% to the original price, the for loop would be used to look at each one. Below is the code that would run this:
What if you had 10.000 products? it gonna be hard and boring! But thanks to the for loop, we can do our tasks very quickly.
The while loop repeats statements as long as a condition is true. In another way, the while loop will stop when the condition is false (e.g., the user types 0 to exit). Each time the loop starts running, it checks the condition.
We can convert the for loop above to a while loop:
Remember that we have incremented the counter, (i). If we had not done this, the loop will run forever, by creating an infinite loop. An infinite loop is one without an exit. To end an infinite loop, press Ctrl + C on your keyboard.
Do – while
The Do – while loop is similar to the while loop, except that the Do – while loop doesn’t adjust the condition for the first time, it is executes a block of statements first and then checks the condition, if the condition returns true, then the loop continues its interaction and if it false, the loop will execute at least once and then it will end.
Let’s re-work the previous loop into a Do – while loop:
This loop will really run one more time, as compared to the while loop. When the counter in the first loop is at 19, the loop will stop running. In the do…while loop, the loop will run and then check the counter. That is why it is able to go through all 20 products.