C++: While and Do While Loops
While and Do While Loops
Reference page for this video tutorial: For and While Loops.
In this C++ lesson, we discuss our first type of loop. Loops provide a means to repeating the execution of a portion of a program. For the moment, we will look at while and do-while loops.
A while loop is a loop that executes as long as a condition is true. For example, this loop runs 10 times since the while condition runs until "iIndex" is 10.
So, this program outputs the numbers from 1 to 10. The same thing can be done with a do-while loop like this:
Why do we have two different ways to do the same thing? Well, there is a subtle difference between these types of loops. The while loop checks the condition before the loop is entered and the do-while loop does not. This means that the do-while loop is always executed at least once.
We might prefer to use a do-while loop, for example, if we were writing code to handle transactions for an ATM. Once the user puts in his card, we assume that he will make at least one transaction, maybe more. So, we might write our code like this:
Of course, we would also have more code in the loop to handle either a deposit or withdrawal. However, once the user supplies a card and puts in his PIN number, we would assume that he would make at least one transaction. For this reason a do-while loop is appropriate.
On the other hand, we can use a regular while loop in a real-time video game. In this example, we use a do-while loop for the main game loop and a while loop for the delay. Typically in a real-time game, we will have a game loop where we will update movements, check for collisions, end of game conditions, etc. At the end of the loop, we will put in a delay to stop the execution until the duration of a time slice has passed. Doing this keeps the game running smoothly. However, we make sure that all of the operations can be handled during a turn's duration.
The screen shot above is from a simple video game that I programmed, where the player shoots down planes overhead from an anti-aircraft gun below. Our typical loop for the game above might look like this:
Of course, in the actual game we would move the gun, plane and bullets, check for collisions, etc. before we stop at the wait loop. Here, the wait loop is the inner while loop and the outer do-while loop is the main game loop.