C++ has three loop structures: for, while, and do-while. Let's see an example of each:
The For Loop
for loops should be used when you know how many times you want to execute a statement, or perhaps it's easier to just say; you should use them when you're working with numbers.
The While Loop
while loops should be used when you don't know how many times a statement should execute.
The Do-While Loop
do-while loops are extremely similar to while loops. The only real difference is that a do-while loop is guaranteed to execute at least one time.
Review Questions
The following are examples of questions similar to what you can expect to see on the next exam.
- What types of loops are used in C++? for, while, and do-while
-
When should a
for
loop be used? When you know how many times you want to execute a statement. - Which loop would you most likely use if you wanted it to run at least once? do-while