If we are starting in the programming world, we've ever came across with a problem that has repetitive code or, also when we're working with array and many other similar situations. In this blog, I'm going to explain what a loop is, its types and some examples.
First, a loop is something that is repeating many times until we decided when it to stop. Taking an example from real life, it could be your daily commute, you go to your work or school every day in the same way. Now, applying it to programming, a loop can execute a specific block code the times we want. The perfect example is a counter, but we'll see this example further in the blog.
Second of all, let's see some kinds of loops and which ones are the most common in real programming. In my opinion, the most used loop is for or foreach. It is perfect to iterate over all the items in an array, since arrays are very common when getting information from databases such as users, products, etc. It also needs a starting counter, a condition to stop and a counter, but not for the foreach loop. While and doWhile is on the second place, this loop a lot less used, but the results are the same. It receives a condition that tells the loop when to stop, this conditions is generally a counter or a boolean that changes inside the loop. Finally, we can consider recurrence a type of loop, but we're not talking of that in this blog.
Last, I'll give you some examples of these four kind of loops. Remember that despite they have slightly differences, a solution can be applied to any of them.
For: Print each element inside a given array.
Foreach: Print each element inside a given array.
While: Print the numbers from 1 to 10.
DoWhile: Print the numbers from 1 to 10.
In short, loops in programming helps us to avoid the use of repetitive code. Also, you now know the most common and useful types of loops and how to use them. Do not forget that you can use any of the reviewed loops to solve the same problem, but some of them are better in very specific solutions.
Comments
Post a Comment