For the Love of Loops!

An all-expenses-paid trip to loops in programming

Let’s start off with the basics. What is a loop?

Complex: A loop is a structure of code that repeats every line of its loop body a set amount of times based upon its conditional statement. (Whew..)

Simple: A loop in programming repeats some code over and over again, a set amount of times.

Structure of a Loop

Now that we know a basic definition, we must now build upon the definition with some vocabulary. Let’s learn the structure of a loop! In its simplest form, this is all a loop is:

Conditional Statement (Checks whether or not we should loop)

{

Loop Body (The code that gets repeated)

}

Now for a more in-depth definition,

Conditional Statement: It’s the first part of a loop, it checks whether or not we should continue on with the loop. If it returns false, we don’t run the loop. If it returns true, we run the loop.

Loop Body: All the parts of code that get run when the conditional statement returns true. Usually surrounded by curly brackets {}, or indicated by indents in the code.

Different Kinds of Loops

We now have all the information required to effectively discuss the different forms of loops in programming!

For simplicity's sake, I will be using the Java programming language to describe these 3 different kinds of loops.

For Loop:

for (int i = 0; i < 10; i++) //Conditional Statement

{//Loop Body}

While Loop:

while (0 == 0) //Conditional Statement

{//Loop Body}

Do While Loop:

do {//Loop Body}

while(0 == 0) //Conditional Statement

Now I know this looks a little intimidating at first, but we will go through the functionality and purpose of every single loop.

For Loops

For loops are one of the most complex loops and are thus the most versatile loop.

For loops are extremely helpful for iterating your loop body a certain amount of times (ex. 10 times, 1000 times, 1 time). They are also extremely compact, and efficient, allowing you to express information incredibly fast.

Let’s look at the conditional statement,

for (int i = 0; i < 10; i++)

First, we start with int i = 0; What this does is it creates a new variable, i, makes it an integer (Any Whole Number), and assigns it to the value 0.

Next, we say i < 10; This is the heart of our conditional statement, this is what returns true or false. Basically, the code checks if the variable i, is less than 10, if it is then run the loop, if it isn’t then stop the loop.

Finally, we must look at i++; This part of the loop basically says “Whenever we are done running the Loop Body, then add 1 to the variable i” This is what allows the loop from becoming an Infinite Loop which we will get to later.

A couple more things on the conditional statement: All these characteristics are not set in stone, you can change i < 10; To i < 100; Or instead of saying i++; You could say i+=10 (Adds 10 to i). Finally, you must understand that the very first part of a for loop int i = 0; Only happens the very first time, while the other two parts happen every single time you run the loop. You must also understand that the variable name i itself is not set in stone, it can also be called whatever you want!

Now you may be thinking that it’s great that you know everything about the conditional statement of a For Loop, but what about the Loop Body! Well, there’s really no point in talking about the loop body because you can do whatever you want for it!

You could say System.out.println(“Hello World!”) which will make your computer say Hello World! as many times as you so chose.

Example of a For Loop:

And here is our result:

This is an incredibly simple for loop that accurately represents an understanding of conditional statements and usage of variables. Try to make your own for loop!

Challenge: Create a for loop that iterates 10 times (1–10), each time printing out the value of i² (Or i*i)

Expected Result: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100

While Loops

While loops are relatively simple and easy to learn.

While loops are most helpful when you are “waiting” for some event to occur. For example, you may want to ask the user to enter a password until they get it correct, this can be easily done with a while loop.

Let’s look at the conditional statement,

while (0 == 0)

The most important part of this statement is the 0 == 0. Let’s dissect each part of this condition. First, we are looking at the value 0, then we are basically checking whether or not it equals the other 0. The way we do this is by using the == operator, which says “Does a equal b?”, and in this case, 0 does equal 0 so it will return true.

Other operators that can be used are < (Less than), > (Greater than), >= (Greater than or equal to), <= (Less than or equal to), and != (Doesn’t equal).

It is also worth mentioning that we can check if a variable is true or false, this is called a boolean. If you are checking whether or not a boolean is true or false, simply type while (variable_name) if the variable is true, it will run the loop, if it is false, it will stop looping.

(You can also use while (!variable_name) which will return the opposite of the value of the variable. True → False, False → True)

So if I were to say while (0 != 0), or “Loop when 0 doesn’t equal 0”, the loop will never run, because 0 does equal 0.

Example of a While Loop:

Result:

As we can see, our while loop ran 11 times, 0–10. Each iteration printed out the next power of 2, till we reacher 2¹⁰ or 1024 as indicated in the conditional statement (num <= 10).

Challenge: Create a while loop that will never end, (ex. 0==0), and make it print out “Coding is Fun” after every loop.

Expected Result: Lots of Coding is Fun

Do While Loops

A do while loop is virtually the same as a while loop except the loop body is run before checking whether or not the conditional statement is true.

The possible benefits of this loop may be that you will always run the loop body once, no matter what. Other than that, you probably won't be using a do while loop at all!

Special Kinds of Loops

Now that you have general knowledge of every single loop in programming, you will now be introduced into some more complex topics surrounding loops.

Infinite Loops

Infinite loops are loops that will never end. For example, if you are doing a while loop and say while(67 == 67), it will always be running since 67 will always equal 67. This will result in either your program stopping itself, or your program crashing. Try to stay away from infinite loops!

The opposite of an inifinte loop is a loop that never runs, watch out for those too!

Nested Loops

The possiblities using nested loops are amazing. A nested loop is a loop inside another loop. For example, let’s say you wanted to create a chess board, you would have a loop that ran 8 times to create each row, and then another loop inside of it that ran 8 times to create each column in each row.

Other examples may be, counting the days in a year, repeating a schedule for each day of the week, or programming a clock.

There is no special way to create a nested loop, all you need to do is write a loop inside the loop body of another existing loop, and tada!

Conclusion

In conclusion, you have learned a ton about loops in programming, and how they function. These loops can be extremely helpful in your programs allowing you to create more versatile, and complex projects.

Get out there and start looping!

Programmer