Please share...

  • Video courses

    All game programming videos just $19 - For a very limited time these three videos and thousands more are up to 90% off!

    Just enter coupon code NEWU19 in cart/checkout

The Unreal Engine Developer Course – Learn C++ & Make Games

Learn and Understand C++

Over 260 video lectures in 44 hours of video!

Learn C++: Beginner to Advanced

Join thousands of successful students!

Loops might sound a bit odd at first? They are a way of executing parts of our C++ code more than once, looping over code until we have the result we want or a test is done. This can simply mean doing the same thing until the code being looped over prompts the loop to end or it could be a predetermined number of times as specified by the C++ loop itself. We won’t be learning all the types of loop that the language has to offer but just enough to advance our game programming.

C++ while loops

The  while loop is nice and straightforward. Think back to the if statements and their conditions. We can use the same combination of operators and variables in the conditional expression of the  while loop. With the while loop we also use an expression that can evaluate to true or false. As with 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 continue to execute until the condition is false. Take a look at this code.

int numberOfEnemies = 100;

while(numberOfEnemies > 0)
{

	numberOfEnemies--;
	// numberOfEnemies decreases by one each pass through the loop

}
// numberOfEnemies is no longer greater than 0

This is what is happening. Outside of the while loop int numberOfEnemies is declared and initialized to 100. Then the while loop begins. Its condition is numberOfEnemies > 0. So the while loop will continue looping through the code in its body until the condition evaluates to false. So the code above will execute 100 times.

On the first pass through the loop numberOfEnemies equals 100 then 99 then 98 and so on. But once numberOfEnemies is equal to 0 it is of course no longer greater than 0. Then the code will break out of the while loop and continue to run after the closing curly brace.

  • Beginning C++ Game Programming

    Beginning C++ Game Programming

    This book is all about offering you a very fast and fun introduction to the world of game programming and C++. It will begin by teaching you the programming basics such as variables, loops, and conditions. In this book there is very little theorizing. If you want a deep discussion of all the ins and outs of C++ concepts look elsewhere. If you are starting from a knowledge of zero C++ and want to build great games- fast, take a look at this book.
    • Setup a C++/SFML/Visual Studio development environment
    • Build a fast, fun Timber clone after learning basic C++
    • Discover the fundamentals of C++ object oriented programming and build a multi-level, top-down 2D, scrolling zombie survival/shooter
    • Explore some advanced C++ concepts and make a side scrolling, co-op split-screen multiplayer platform game with directional sound, particle effects and your very own level designs!
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)
    C++ for Game programmers book

    C++ For Game Programmers

    Already know the basics of C++ but want to dig much deeper in an entirely game-focussed context? C++ for Game Programmers is that book. This best selling title supplements your knowledge by putting everything into perspective from a game-development point of view. The book points out the most effective C++ practices and steers you away from the potentially dangerous ones. It describes common C++ techniques to solve specific problems most game developers face.
    • From a gaming perspective, learn about inheritance, performance, memory management, and STL to object creation, object serialization, and scripting languages
    • Explore C++ Design Patterns and high-level problem-solving constructs that are most commonly found in games
    • Discover custom Structures and algorithms, which provides a detailed hands-on discussion of using C++ to create efficient solutions to difficult problems in a highly structured manner
    Amazon USA
    Amazon UK
    Amazon CA
    Game Programming Patterns book

    Game Programming Patterns

    If you are serious about writing high quality, reusable, efficient code using C++ or indeed any other language, then inevitably you will need to seriously hone your knowledge of game programming patterns. If you don't know what game programming patterns are they are simply the solutions to design problems. If you have programmed even a basic game you will have noticed that the code gets long and hard to manage, very quickly. The more features you add the more sprawling and messy your code gets. In addition to usability/reuse-ability, our game code needs to be efficient enough for the game to run smoothly. That's what this book will do for you.
    • Learn to write a robust game loop, how to organize your entities using components, and take advantage of the CPUs cache to improve your performance
    • Discover how to organize your entities using components, and take advantage of the CPUs cache to improve your performance.
    • Never again wonder what is the "best" way to organize your game code
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)

Just like a  if statement, it is possible that the while loop will not execute, even once. Take a look at this.

int availableCoins = 10;

while(availableCoins > 10)
{

	// more code here.
	// but it will never run unless availableCoins is greater than 10

}

Moreover, there is no limit to the complexity of the expression or the amount of code that can go in the loop body.

int playerLives = 3;
int alienShips = 10;

while(playerLives !=0 && alienShips !=0 )
{

	// Entire game code here.
	// ...
	// ...
	// etc.

}
// continue here when either playerLives or alienShips = 0

The above 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 the value of false part way through as it is not tested again until the code tries to start another pass. For example.

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!

}

The above loop body will execute once. We can also set up a while loop that will run forever; unsurprisingly called an infinite loop. Here is one.

int y = 0;

while(true)
{

	y++; // Bigger..... Bigger...

}

Breaking out of a while loop

We might use an infinite loop like this so that we can decide when to exit the loop from within its body. We would do this by using the break keyword when we are ready to leave the loop body. Like this.

int z = 0;

while(true)
{

	z++; // Bigger.... Bigger.....

	break; // No you're not haha
	// Code doesn't reach here

}

And you might have been able to guess that we can combine any of the C++ decision-making tools like if, else, and switch with our while loops and the for loop we will learn about as well. As an example.

int x = 0;
int max = 10;

while(true)
{

	x++; // I am going to get mighty big!
	if(x == max){
		break;
	} // No you're not haha.

	// code reaches here only until max = 10

}

It would be simple to go on for a long time demonstrating C++  while loops but at some point, we want to start making games. So here is one last concept concerned with loops.

 C++ for loops

The for loop has a slightly more complicated syntax than a  while loop as it takes three parts to set up. Have a look at the code first then we will break it apart.

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 after each pass through loop)

To clarify further we have:
Declaration and initialization: We create a new int variable i and initialize it to .
Condition: Just like the other loops, it refers to the condition that must be true for the loop to continue.
Change after each pass through the loop: In the example i++ means that 1 is added/incremented to i on each pass.

for(int i = 10; i > 0; i--)
{

	// countdown

}

// blast off i = 0

The for loop takes control of initialization, condition evaluation and the control variable on itself. We will use for loops in a game project quite soon.

We have learnt a lot of C++ concepts, keywords, and structures. It is probably easy to imagine how our code could quite quickly become long and sprawling. So let’s look at how we can organize our game using C++ functions.