Going around in circles! - Looping in software.
This time we look at the ways we make our code loop, so that we run a piece of code multiple times.
Loops are what we use when we want to do something repeatedly. Say we need to print something on the screen more than once, or play a sound over and over, until the user responds to us.
As is often the case with programming, there's more than one way to do a loop in software. In this episode, we look at three common ways to loop:
Today's episode, on YouTube - Part 1: while and for loops
A while loop looks something like this:
The while loop is useful in situations like this, where a collection of data already exists, and you need to inspect it, but maybe you do not know ahead of time how much data there will be.
A for loop consists of two sections:
Provided that the loop control says it's OK to repeat the loop, the for-loop with run the List of commands over and over.
This is quite complex for a for loop, but it has the advantage of keeping all the looping logic in one place. It looks like this:
A concrete example would be that the initializer creates a variable count and set it to zero (count = 0). In the condition-check of the for-loop you could look at count, to confirm it is not eight (8 != count). Provided the condition check is true, the for-loop will run the List of commands. After all the commands execute, the post-iteration runs. You may, for example add one to the value in count. The for loop will then automatically repeat from condition check. In this example, the list of commands would be repeated eight times.
List of Commands
Putting it all together, a for-loop would look like this:
With recursion you do not have any special loop instructions. What you are doing is writing a function which calls itself at some point, causing a loop. It's important for a recursive function to have an exit criterion. If a function calls itself it will repeat forever unless at some point it stops calling itself.
Here's a simple example of a recursive function that uses addition to multiply two numbers