Looking for in-depth C tutorials? Try SourceCrunch.
When creating applications in C++, it's often extremely useful to be able to use the programming concept of a loop. This is a piece of code that repeats while a certain condition is true. In this tutorial, we will be learning how to use the two most basic kinds of loops -- the
while loop and the
The while loop is the simplest of loops in C++ and pretty much does exactly what we defined in the basic introductory paragraph. It loops a piece of code while a certain condition is true. The loop is created using the
while keyword, followed by a condition in brackets (you already know how to formulate these - they are exactly as found in if statements!), followed by the code you want to execute in curly brackets. Remember that we can also use a bool value as the condition if we want -- as in if statements, it's all about whether
false is returned.
So let's get some test code running. One of the simplest (and most common) examples in C++ is simply counting up numbers. If we create an integer variable and set it to 0, create a while loop that executes code while the number is less than or equal to 5, output the integer variable in the loop and then add one to the number during the loop - we should have a loop that goes round 5 times and counts up to 5 (think about it, the logic all makes sense). The code might be something like the following:
1 2 3 4 5 6
On running this code, you should see that it all works as planned! The program counts up from 1 to 5 and hence the loop and condition were formulated correctly. It's worth noting that adding one to the variable is called 'incrementing' it, and can be accomplished via many methods (
number = number + 1,
number += 1;, and some other we'll cover in the future).
Obviously loops aren't only useful for counting up numbers (although they are very good at that, as we've seen!) -- let's say we wanted to only move the program on after the user had entered a 'valid' number into the program for example. We could create a loop that only breaks after the input has been validated! Booleans (
bools) serve a perfect purpose for this, and so we could do something like this:
1 2 3 4 5 6 7 8 9 10 11 12
It's worth noting that the code above could also work by using
while(true) (an infinite loop) and then using
break; to break out of the loop if the input is valid.
Increment and Decrement operators
In order to progress onto 'for' loops, we're just going to learn a little bit about incrementing and decrementing using some operators built into the core language of C++.
Remember the while loop code we wrote earlier in this tutorial? We wrote
number = number + 1 to add one to the variable
number that we were using at the time, to step through the while loop a certain number of times. We glossed over the fact that this was called incrementing and that there are a variety of ways to do it. The first I've just covered, the second is using the
+= operator to do something like
number += 1, but there is also a third, even easier way to accomplish this. This way, unlike the others, can only be used to add one to a variable rather than adding a number of your choice. This method is using something called the increment operator. The increment operator is shown in C++ by writing
++ on either the left or right side of a variable - as you might expect, it increments that variable.
So if we were to go back and re-factor our while loop code to make it use the increment operator instead of using the current, stretched out method - we would end up with something like this:
1 2 3 4 5
There we go, doesn't that look a bit better! What's great about this is that you can also use the variable while it's being incremented, for example in a simple
cout! It's important to note that the operator does different things when put at different sides of a variable - this can be seen most noticeably when using the variable while incrementing as previously described. So firstly let's use the post-increment (the one with the
++ after the variable name), this should use the variable and then increment it. For example the following will output 10, then 11:
1 2 3
In contrast to this, using the pre-increment (the one with the
++ before the variable name) will increment the variable before using it. So the following should output 11, then 11:
1 2 3
A small difference, but incorrect usage in a program could completely screw up a system.
Decrementing is extremely similar to incrementing, however minuses one from the variable instead of adding one. The decrement operator, rather unsurprisingly, is
-- and just like the increment operator has pre and post versions (which act just like the increment ones). I'm not really going to go into much depth here, as it should be blindingly obvious how to use the decrement operator if you know how to use the increment operator correctly. Take the following pieces of code for example, try and guess what will output what:
1 2 3
1 2 3
If you're stuck, try re-reading the incrementing section or just compiling the code to see the results. Just remember, the post operator always does the operation after usage, and the pre operator always does the operation before usage.
The "for" loop is essentially just another kind of loop, much like
while. It, however, makes creating a loop which should loop a certain number of times really simple.
Perhaps one of the best ways to show off the "for" loop is to simply cycle through and output all the elements in an array. So first, let's just create an array that we can cycle through inside of our
main function - I'm going to use an array of
strings (make sure to
Now we have the array, let's start creating the loop itself. The "for" loop is created by using the
for keyword, and then specifying three different sections, separated by semicolons, inside brackets. Code to execute each loop is then put inside curly brackets that follow this. The first section that the loop takes is called the declaration, and should contain the declaration (and probably initialization) of an iterator variable that the loop will use - just like the
int number; variable we used with some 'while' loops. The second section is called the condition - this should contain the condition which must remain true for the loop to keep going. The third and final section, is called the update - this should contain some code which updates the iterator variable (for example, incrementation). The general idea should look something like the following:
1 2 3 4
All we have to do now is populate the sections. Something like the following will do fine to loop round 10 times (with
i going from 0 to 9):
1 2 3 4
The real power of the 'for' loop then comes from using 'i' inside the loop. 'i' should get incremented each time, and so 'i' will contain the values 0-9 in different stages of the loop - we could use this to simply count up, or to do other more interesting tasks. It's worth noting while we're talking about the sections of these loops, that not all sections are necessary. If you wanted an infinite loop that uses
for for example, you could leave all the sections empty and simply write:
1 2 3 4
break; could be used to break out of the loop at any point inside of it. Getting back to our purpose of looping through an array though, we want to execute the code inside as many times as our array has elements. We could hard-wire it in and have it loop round exactly five times and access element 'i' each stage of the loop, but this isn't the most elegant solution as we may wish to change the number of elements in the array at a later date, at which point we would have to update all the code (which isn't what we want). A better solution might be to get the exact number of elements in the array, but unfortunately there isn't a nice function or anything to do that -- we can however count the number of elements if we get a bit creative.
There are a number of ways to go about doing this, but by far the easiest way to do it in our case is to divide the total size of our array (in bytes) by the space each element takes up (in bytes). There is a function that can get the size of stuff (in bytes), and that function is called
sizeof. With all of this in mind, the calculation to get the number of elements should look like the following:
Note that although we are dividing by the
sizeof the first element in the array above, the result would be the same if we divided by
sizeof(string) -- using the first element in the array is just slightly more flexible as we may wish to change the array datatype in the future (although hopefully not to anything too complex as this method of counting the elements doesn't work with everything).
So now we can count the elements in the array, writing out the for loop shouldn't be too difficult. We want to create an iterator variable, which we'll call
i, loop while it is less that the number of elements (the calculation we just worked out), and then increment
i each time. The result should look something like the following:
1 2 3 4
From here, all we need to do is add the
cout that outputs the array element with the index of
i, i.e. all of the array elements from index 0 to index 9 - and we've finished our program! When outputting many numbers it can get confusing for the user, so it might also be a nice idea for the application to number each score it outputs -- what better way to do this than make use of the index number! We've covered everything necessary to create this program - if you feel like a challenge, try to create it all by yourself, if not, feel free to take a look at the code I whipped up below (with a little bit of extra
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17