C Nested Loops

C Nested Loops

Breaking out of a loop

The C++ statement called break provides a way to break out a loop early. The break statement is placed within the body of the loop usually as part of an if statement.


In the example, the loop is set to run a maximum of 50 times but the user can quit the loop at any time by specifying a specific input, q in this case.

sample loop that has a break statement

Should you use break?

The use of break statements is not recommended. We expect the iteration of a loop to be controlled by the true/false statements in the while and do-while and the for loop header sections. Adding a means to suddenly stop the loop outside of the normal approach can make code difficult to understand and debug.

We can rewrite the above code to stop when the user enters q without having to use a break statement such as follows.

sample code using a quit option instead of a break

Using break in a nested loop

In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

Video lecture

Nested Loops - by Jennifer Parham-Mocello