Loops
In programming, we often need to do the same thing more than once. The obvious example that we have seen so far is the game loop. With all the code stripped out, our game loop looks like this:
while (window.isOpen())
{
}
There are a few different types of loops, and we will look at the most commonly used ones here. The correct term for this type of loop is a while loop.
while loops
The while loop is quite straightforward. Think back to the if statements and their expressions that evaluated to either true or false. We can use the exact same combination of operators and variables in the conditional expressions of our while loops.
Like if statements, if the expression is true, the code executes. The difference with a while loop, however, is that the C++ code within it will repeatedly execute until the condition is false. Take a look at the following code.
int numberOfZombies = 100;
while(numberOfZombies > 0)
{
// Player kills a zombie
numberOfZombies--;
// numberOfZombies decreases each pass through the loop
}
// numberOfZombies is no longer greater than 0
Let's go over what's happening in the previous code. Outside of the while loop, int numberOfZombies is declared and initialized to 100. Then, the while loop begins. Its conditional expression is numberOfZombies > 0. Consequently, the while loop will continue looping through the code in its body until the condition evaluates to false. This means that the preceding code will execute 100 times.
On the first pass through the loop, numberOfZombies equals 100, then 99, then 98, and so on. But once numberOfZombies is equal to zero, it is, of course, no longer greater than zero. Then, the code will break out of the while loop and continue to run, after the closing curly brace.
Just like an if statement, it is possible that the while loop will not execute even once. Take a look at the following code:
int availableCoins = 10;
while(availableCoins > 10)
{
// more code here.
// Won't run unless availableCoins is greater than 10
}
The preceding code inside the while loop will not execute because the condition is false.
Note that there is no limit to the complexity of the expression or the amount of code that can go in the loop body. Consider the following hypothetical variation of our game loop:
int playerLives = 3;
int alienShips = 10;
while(playerLives !=0 && alienShips !=0 )
{
// Handle input
// Update the scene
// Draw the scene
}
// continue here when either playerLives or alienShips equals 0
The previous while loop would continue to execute until either playerLives or alienShips was equal to zero. As soon as one of those conditions occurred, the expression would evaluate to false and the program would continue to execute from the first line of code after the while loop.
It is worth noting that once the body of the loop has been entered, it will always complete at least once, even if the expression evaluates to false partway through, as it is not tested again until the code tries to start another pass. Let's take a look at an example of this:
int x = 1;
while(x > 0)
{
x--;
// x is now 0 so the condition is false
// But this line still runs
// and this one
// and me!
}
// Now I'm done!
The previous loop body will execute once. We can also set up a while loop that will run forever, and unsurprisingly is called an infinite loop. Here is an example:
int y = 0;
while(true)
{
y++; // Bigger... Bigger...
}
If you find the preceding loop confusing, just think of it literally. A loop executes when its condition is true. Well, true is always true, and will therefore keep executing.
Breaking out of a while loop
We might use an infinite loop so that we can decide when to exit the loop from within its body rather than in the expression. We would do this by using the break keyword when we are ready to leave the loop body, perhaps like this:
int z = 0;
while(true)
{
z++; // Bigger... Bigger...
break; // No you're not
// Code doesn't reach here
}
In the preceding code, the code inside the loop will execute once, upto and including the break statement, and then execution will continue after the closing curly brace of the while loop.
As you may have been able to guess, we can combine any of the C++ decision-making tools such as if, else, and another that we will learn about shortly, known as switch, within our while loops and other loop types as well. Consider the following example:
int x = 0;
int max = 10;
while(true)
{
x++; // Bigger... Bigger...
if(x == max){
break;
} // No you're not
// code reaches here only until max = 10
}
In the preceding code, the if condition decides if and when the break statement is executed. In this case, the code will keep looping until max reaches 10.
We could go on for a long time looking at the various permutations of C++ while loops, but, at some point, we want to get back to making games. So, let's move on to another type of loop: the for loop.
for loops
The for loop has a slightly more complicated syntax than the while loop because it takes three parts to set one up. Take a look at the following code first. We will break it apart after:
for(int x = 0; x < 100; x ++)
{
// Something that needs to happen 100 times goes here
}
Here is what all the parts of the for loop condition do:
for(declaration and initialization; condition; change before each iteration)
To clarify this further, here is a table to explain each of the three key parts, as they appear in the previous for loop example:
We can vary for loops so that they do many more things. Here is another simple example that counts down from 10:
for(int i = 10; i > 0; i--)
{
// countdown
}
// blast off
The for loop takes control of initialization, condition evaluation, and the control variable. We will use for loops in our game, later in this chapter.
Now, we can move on to the topic of C++ arrays, which help us store large amounts of related data.