Cookies   I display ads to cover the expenses. See the privacy policy for more information. You can keep or reject the ads.

Video thumbnail
Hello, in this episode we're going to look at the 4 different types of loops.
Let's start with the most common one, the for loop.
To create a for loop, we write the keyword 'for', followed by a pair of parentheses,
and then a pair of curly brackets.
Now inside the parentheses we have three sections, separated by semicolons.
The first section is the initializer, the second is the condition, and the third is
the iterator.
The initializer section is where we create a local variable, usually an integer, which
is conventionally called 'i', but you can make it anything you want of course, and we
initialize it to some value.
In the condition section we then state the condition that must be true in order for the
loop to run.
So for example, we might say: run while i is less than 10.
Finally, in the iterator section, we can modify the value of our variable, so for example
we might have i++, meaning i increments by 1 each time.
Between the 2 curly brackets we can now write the body of our loop, which I'll make simply
print out the value of i.
If we run this code, we'll see that it prints out the values from 0 to 9.
So if we think through this step by step, it should be clear how the loop works.
First the variable i is created and set to 0.
The condition i<10 is true, so the code in the body of the loop runs once, printing out
Then the iterator section runs, increasing the value of i from zero to one.
The condition is still true, so the code runs again.
This repeats until i is increased to 10, at which point the condition is no longer true,
so the loop terminates, and the code resumes running from outside the loop.
This sort of loop is often useful for setting the values in an array.
For example if we're wanting to store the first 20 powers of 2, we could create a new
int array with a size of 20, and then loop from int i = 0, while i < powersOfTwo.Length,
i ++.
Remember that, since arrays are indexed starting at zero, their last element has an index of
one less than their length, which is why we have the loop run while i < powersOfTwo.Length,
and not while is i <= to powersOfTwo.Length.
Now, inside the loop we can simply have powersOfTwo, with an index of i, = 2^i, using the Mathf.Pow
Of course, we don't have to start the loop at zero and inrement by one each time, although
that is how its usually used; as an arbitrary example we could: initialize int i = 100;
and then while i > -80; decrease i by 30.
Alright, now how about looping through multidimensional arrays...
Say we have an 8x8 integer array, representing a chess board, and we want to set it so that
light squares have a value of 0, and dark squares have a value of 1.
To achieve this, we can use two nested for loops.
So we start with one for loop to determine the row index, so I'll make a loop with int
row = 0, row < board.GetLength(0), row ++.
Note this getLength method, which allows us to specify which dimension of the array we
want to know the length of.
So index 0 refers to the first dimension.
Inside this loop, we can then have another loop, with int column starting at 0; while
column < board.GetLength(1); column ++;
So hopefully this makes sense: The outer loop starts with row equal to 0, and then the inner
loop begins, so we get a column value of 0, then 1,2,3,4,5,6,7, after which the inner
loop terminates, and so the outer loop gets to run again, and row is increased to 1.
This process repeats until row is no longer less than 8, at which point the outer loop
To actually assign to the array, we can say board, with an index of row, column, is equal
to (row+column) mod 2.
Remember that the modulus operator will divide the first number by the second number, and
return the remainder.
This operation achieves the result we want.
Now the second type of loop we'll be looking at in this video is the 'while' loop.
A while loop simply runs while a certain condition is met.
So perhaps we have a bool called doingSomething, which we set to true.
We can then say while(doingSomething), and now this loop will run until the doingSomething
bool is set to false.
So writing while (true) \, is one way of creating an infinite loop.
Now there's nothing a while loop can do, that a for loop can't, and vice versa.
For example, the following code will make a while loop work like a for loop, but it's
not as concise as using a for loop.
In the same way, if we leave out the intializer and iterator sections of the for loop, and
just make use of the condition section, then we've got the same behaviour as a while loop,
but the syntax is kind of strange with these two extra semicolons.
So you can see that both loops serve a specific purpose.
In general, we use a for loop when a specific number of iterations is required; and we use
a while loop when the number of iterations is unknown, or difficult to calculate.
We've already seen a practical example of where a for loop is useful, that being assigning
values to an array; but you can imagine many more, such as spawning a certain number of
enemies into a game, and so on.
It's more difficult to imagine cases where you don't know how many times you want a loop
to run; but as one concrete example -- the first step in some 2D dungeon generation algorithms
is to start with a bunch of rectangles for each room, and then to keep nudging the away
from one another until they no longer overlap.
Obviously you can't know in advance how many iterations that will take, which is why the
while loop is an appropriate choice.
We'll see another practical example of while loops next episode.
The third type of loop is very closely related to the while loop, and is called the do while
How this works, is you write the keyword do, folowed by the body of the loop, and only
after the body do you write the condition.
The behaviour is exactly the same as a while loop, except it only checks the condition
at the end of each iteration of the loop.
As a result, if the condition is false to start with, the code in the loop will still
run once before terminating.
I've found that I very seldom need to use a do while loop, but it's good to know it
exists for those rare occasions.
The final type of loop is called the foreach loop, and this is used to iterate over a collection
of items, such as an array, or a list.
We've already seen how a for loop can be used to iterate over a collection, but for situations
when you're not assigning to the collection, but simply want to retrieve the values, then
the foreach loop is a little bit more concise.
Say we have an array of strings, called possibleNames.
The syntax for the foreach loop is as follows: first the keyword foreach, and then, inside
parentheses we declare a variable of the correct type - in this case string - to hold the value.
I'll call it name.
We then indicate that we're looping through each element IN the possibleNames array.
If we now print out the name variable, you can see that with each iteration, it has been
assigned the next value in the array.
Note that you cannot
Now there are two keywords you might sometimes find useful when working with loops, and these
work the same way for any of the four types of loops.
These keywords are 'continue' and 'break'.
Continue simply skips one iteration of a loop.
So for example if we have a for loop printing the numbers from 1 to 10, and I write if (i==5)
\{continue\}, then it will skip the rest of the code in the body of the loop for that
iteration, and so the ouput will be 1,2,3,4,6,7,8,9,10.
The break keyword can be used to terminate a loop prematurely.
So if I add the lines, if (i==7) \{break\}, then the loop will immediately terminate at
that point, and so the output will be 1,2,3,4,6.
As an example of when this keyword might be useful, imagine we have some game in which
the player attempts to open a locked door.
We might loop through each of the slots in the player's inventory, to see if that slot
contains the correct key for the door.
If we find the key, however, there's no need to keep searching, so we can use break to
terminate the loop.
Alright, to recap: For loops are used when a specific number
of iterations is required, whereas While loops are used when the number of iterations
is unknown.
Do while loops are the same as while loops, but the code inside them will always run at
least once, even if the condition is false from the outset.
Foreach loops can be used to retrieve elements one-by-one from a collection.
The continue keyword can be used to skip to the next iteration in a loop, and the break
keyword can be used to terminate the loop.
Alright, that's everything for this episode.
Until next time, cheers!