Today we are going to talk about a fundamental concept in programming, loops, and iterators. Loops and iterators are some the most common programming concepts and you will find them in one form or another in almost all modern programming languages. Lets first start with loops; loops are used when you have a repeating routine or sub routine, where you may be calling a whole function multiple times, or just executing a simple piece of code the important part of loops is that is an easy and modular way to execute a sequence of code multiple times. For these examples we will be using ruby as is very readable and has a lot of different loops and iterators, but we will not touch on all of them. First and most simple loop is while loops; while loops will execute the piece of code while a condition is met hence while loop. Real life example would be while meat is raw cook; here is a code example of a while loop in ruby.
x = 5
while x <= 0
puts x
x = x - 1
end
This simple piece of code will just run and minus one from x until it is zero, nothing fancy put hopefully its helpful. Here is another diagram.
For our next loop we will cover for loops another extremely common type of loop. For loops like while loops it executes the loop while a condition is met but it only revolves around an increasing value, with that value being automatically updated right when the condition is called. Here is an example of a for loop.
x = 5
for i in 1..x do
puts i
end
This section of code will update i until it is equal to x which in this case is 5, and with each pass over of the loop it will print it. So, the console will print 1, 2, 3, 4, 5 (each in a newline without comma). For good measure here also how to do this same code in a while loop, as well as a diagram of how for loops work.
x = 5
i = 1
while i <= x
puts i
i = i + 1
end

Now that we’ve cover the two most common loops let move onto iterators. Iterators are an object that allows us programmers to traverse a container of elements/values, most commonly lists (1). For these examples we will be using arrays; the type of iterator we will be using today is “dot each” or written code as .each. Dot each is what it is called in Ruby but it is commonly called For each in other languages with a slightly more complex syntax. Dot each will simply iterate over every element of the list and execute some piece of code for each element. Here is the syntax for a dot each iterator in Ruby.
names = ['Bob', 'Joe', 'Steve', 'Janice', 'Susan', 'Helen']
x = 1
names.each do |name|
puts "#{x}. #{name}"
x += 1
end
In this example given the array of names you are printing x which is counting with the names and the name itself.
I hope this brief demonstration of loops and iterators was helpful, please look up more documentation on loops and iterators if you are curious. Make sure to look up all the types of iterators and loops in your language of choice as they might add much readability and efficiency to your project.
Sources: