Learn to use Loops in C++

You can access the full course here: C++ Foundations

While Loops

Now that we can perform tests and execute code once, the next step is to be able to perform tests and execute code multiple times as long as some condition continues to be true. For this, we use loops. Loops provide a way to execute code multiple times without having to type the same code again and again.

The simplest form is the while loop and it acts very much like an if statement run multiple times. It performs a test and executes code if the test returns true but instead of executing the code once, it continuously executes the code until the test eventually returns false. This can be dangerous because if the test never returns false, the loop will run infinitely and the program will crash so we need to make sure that we build the loop in such a way that it will eventually exit.

Games at their heart, often contain a big game loop that continuously performs checks, handles player interaction, renders graphics, etc. as long as the game is still running and breaks when the user does something to end the game. We can build a very very simplified version of this by moving a player as long as they are not quite at the end position and then exiting the loop when they are. We first need current and end position variables:

int pos = 0;
int endPos = 5;

Then we need a way to check if we are at the endPos and if not, move our player forwards. An if statement will only do it once so we need a loop which loops like this:

while (pos < end_pos) {
  pos += 1;
  std::cout << pos << “n”;
}

The difference is that the while loop loops to the top and executes the test and code continuously until eventually, in our case, the pos >= endPos. In this case, it will run 5 times. We know that this will eventually stop because our pos < endPos at the start and we’re increasing it by 1 each time.

For Loops

The next type of loop is the for loop. This acts similar to a while loop but it runs a set number of times. We build right into the loop when to start and when to stop so we know how many times it will run. This makes it great for pairing with collection types as we can just set the start point to be the beginning of the collection and the end point to be the end and visit each element in the collection. We can set up a for loop like this:

for(int i = 0; i < endPoint; i += 1) {

}

Not all for-loops have to be set up with these exact numbers; we can change the start value of i, the end condition, or the step value ( += 1 ). This one just starts with a value of 0, increases i by 1 each time, and runs until i < endPoint returns false. For example, if we wanted to print out every member in an array, we could do something like this:

int intArray[] = {5, 4, 3, 2, 1};
For (int i = 0; i < 5; i += 1) {
  std::cout << intArray[i] << “n”;
}

This uses i as an indexing variable with the initial value run to be 0 and the final value run to be 2 and uses that to visit each element of the array. i starts at 0, then 1, then 2, then we exit the loop when i = 3. We don’t have to use i; sometimes we just want to perform a task a set number of times and that’s where for loops excel. Go ahead and run the loop within the main function to print out each element.

The final thing about loops is that every for loop can be turned into a while loop but not every while loop can be turned into a for loop because sometimes we don’t know how many times a while loop will run but we always know how many times a for loop will run.

 

Transcript

While Loops

Hello guys welcome to our tutorial on While Loops. Here we’re going to first introduce the concept of loops, and then we’ll explore the first and simplest kind. So we’re going to start by covering what are While Loops, then we’ll just write and run a very simple example. So let’s head to the code and begin.

Right, so before we write any actual code let’s talk about what While Loops are, and what they bring to the table. Well, a loop in code is just a way to execute the same statement or set of statements multiple times by racing it just once, putting it within a loop and running the loop. Okay, so this is hugely beneficial for us because we don’t want to have to rewrite the same code over and over again, if it’s doing exactly the same thing. It’s much easier to write it once, run it many times, than to write it many times and then run it once.

Okay, so a while Loop is the simplest form of it. And it actually acts very very similar to an IF statement. It will execute some code if some test returns True. The difference is that it will continue to execute the code, as long as that case is True. So if the case never returns False, then it will always execute the code over and over again infinitely until the program crashes. So that’s bad. But if we design our While Loops carefully, we can prevent this issue and control exactly how many times we want it to run.

Now what we can do is we can simulate a very very basic kind of platform runner. Typically the way these games work, is there’s an endpoint your current position, and then you have to get to the endpoint, by jumping over obstacles, defeating enemies et cetera, and the game is over or at least the level is over as soon as you reach the endpoint. So to simulate that, we might use a While Loop. We could have an Integer that represents a current position or just Pos for short. Maybe we start at zero, have an Integer that represents the end position, maybe we’ll just set this equal to five. Okay?

And what we’re trying to do is basically keep moving forwards until we reach the end. So we might use a While Loop for this will basically say something like, as long as our position is less than our end position, we’ll continuously execute some code and quit missing one of those. Okay? So in this case we might want to increase our position by one. So we’ll do in Pos plus equals one, and then maybe we want to print out our current position. So we can do Standard C out our Pos and we’ll do a new line as well. Okay, so we’ll do that and then just the new line character.

Okay, so let’s go ahead and run this. How many times do you think this will run? It should run five times. Okay? The reason it runs five times is because our end position is five. We start at zero. When we get to the first iteration, we perform the check, zero is less than five. So we execute the code, just increase it’s position by one, prints out and then loops back up to the top. We perform the test again. Yep, one is still less than five So we execute the code.

Now two still less than five. So we execute the code on and on, until eventually position is equal to five. We go back up to the top, we perform this test and it returns False. Because five is no longer less than five, at which point we exit out of the loop. So we skip over this code and that’s it. Okay,then we could execute any code down here okay, so that’s your basic While Loop.

Again there is the issue that if you don’t design this carefully, you can end up having it run forever. So you always want to make sure there is a way to exit out of your While Loops, or that eventually they will end okay? Otherwise that’s pretty much of it for the basic While Loop. Again really just think of it as an IF statement that continuously runs rather than just runs once. In the next section, we gonna be covering the For Loop So definitely play around with While Loops a bit.

Make sure you’re super comfortable with them. And we’ll learn about the next loop type in the next section. Okay? so stay tuned for that Thanks for watching and see you guys there.

For Loops

Hello, everyone. Welcome to our tutorial on For Loops. This is the next type of loop, the for loop, it’s a bit more restrictive, but that also makes it potentially easier to use than the while loop. So we’re going to start by covering what are for loops, then write and run for loops, and of course compare and contrast them to while loops. Let’s enter the code and get started.

Okay, so previously, we talked about while loops, hopefully you’re comfortable with those, because a for loop is actually gonna run fairly similarly to this. Again, it’s just another mechanism by which we can execute the same code multiple times. The difference here is that for loops are always going to run a set number of times. We choose exactly how many times we want the loop to run by; specifying a start point and end point and then some sort of a step or an iterator variable, okay? So we need these three items when designing a for loop. That makes it a bit more tedious to set up but ensures that it will run a set number of times.

So it looks a bit like this. We have for, we have the start condition, the end condition, and then the step variable. Okay, so to set up a basic loop, let’s say that runs five times, what we would do is we would create an int i equals zero, so we’re starting with i equal to zero, we’re ending when i is no longer less than five, and we’re increasing i by one each time, okay?

So this is a very basic for loop that will run five times, okay? Again, because we’re starting at zero, we’re executing the code and then we increase i by one at the end, we go back up to the top, i is equal to one now. We check to see if we’re at the end condition, if not, we execute the code, increase it by one, and so on and so forth until eventually i is no longer less than five.

Now, this makes it very good to pair with arrays because we can use i as the indexing variable within an array and then we can just set it to run for as many elements are in an array. So let’s actually demonstrate that.

We’ll just have maybe an array of integers, maybe we’ll just do the numbers five, four, three, two, one, so nothing terribly exciting. We’re just going to create an array of ints, maybe just be like intArray. Okay, and we’re just gonna set this equal to five, four, three, two and one. Okay, so really, again, nothing terribly exciting. What we’ll be doing is printing these guys out. So we’ll just do a standard cout and we’re just going to do the intArray at the index of i and then of course, a new line character.

Okay, so essentially, with each loop iteration, we’re guessing the intArray value at the index of i, so it starts at zero, then one then two then three then four and then exits. So it will start at five then four, three, two, one, and then will exit, okay? So if we save this and we run it, then we’ll basically be printing out the numbers five, four, three, two and one. And there we go, okay?

So we can use i as the indexing variable, although we don’t have to, we can just set this loop to run five times, you don’t necessarily have to use i as an indexer. But that’s very often where you’ll be using for loops, okay?

So to compare and contrast them to while loops, essentially, we’ll use for loops where we know exactly how many times we want the loop to run. We use a while loop when we’re not 100% sure how many times it will run, such as with a game. With a game loop, the game could be over in a minute, it could be over in five hours, okay? So the loop needs to run continuously throughout that. When we’re iterating through in array, there’s a finite number of elements thus we know exactly how many times we’re going to be running the loop, and that’s why we’d use a for loop, okay?

So practice around with for loops. I know it looks a bit more complex, but really, it’s no different from a while loop. It’s just a bit more strict. Now the one restriction here is that every single while loop or every single for loop can become a while loop, but not every single while loop can become a for loop, okay? So try and think about that. When we come back, we’re gonna be talking about functions. So stay tuned for that, thanks for watching and see you guys in the next one.

 

Interested in continuing? Check out the full C++ Foundations course, which is part of our One-Hour Coder Academy.