Lesson 10.1: Loops – The Basics
In our last lesson we took a look at conditional statements, then went more in-depth in discussing the first type: the branching conditional statements. In this lesson we’re going to talk about the other type: the looping conditional statements (also just called loops).
What are Loops?
As I mentioned briefly in Lesson 9, loops basically will “loop” through a portion of code, going through all the code then looping back to the start when it reaches the bottom, as long as the condition is true.
Up until now, all of the code we’ve discussed has moved in a very linear path, straight down, line by line (with the exception of our branching conditional statements, which may skip a few lines). With the addition of loops, we’ll now be able to repeat portions of code multiple times without having to rewrite the code multiple times.
What Are Loops For?
For a simple example, let’s say we wanted to Print 12345. Doing it without loops would look something like this:
Print "1" Print "2" Print "3" Print "4" Print "5"
With a loop (in this case, a for loop), it’d be something like this:
For Integer i = 1 While i <= 5 Increment i = i + 1
Print i
End For
With both of those, we would get the same output, but our loop version is a lot easier. You may say “big deal, it’s 2 lines shorter”, but imagine if you wanted to count from 1 to 10,000 or a million. Then the for loop would be several thousands of lines shorter.
Loops are also used when something needs to be done over and over again. In fact, right now there are probably several (if not dozens) of loops being run on your computer at this very moment. For example, on your operating system, each loop your operating system is causing your screen to redraw what it is displaying (if necessary). If you have an instant messenger running, it is constantly looping to check for new messages, see if friends have logged on or logged off, etc. In video games, it will loop around and each loop it will check for user input, make enemies move, etc.
As you can see, loops can be very useful.
In this lesson we talked about what loops are and the premise that they operate on. In the next portion of our lesson we’ll discuss the specifics of three common types (and two non-as-common types) of loops: for, while, do…while, foreach, and do…until.




