C++: For Loops

For Loops

In this C++ tutorial, we cover the other major type of loop: namely, for-loops. For-loops offer a more compact form than a while-loop when we are writing most loops. By taking the key common elements of a loop and making them part of the loop statement, for-loops offer a less error-prone looping structure. We have chosen to call these elements initialization, conditional, and update:

In the video, we gave the example of a for-loop that was used to output the prices for a list of homes and the corresponding location by district. The example is not necessarily practical or common in real estate, but in real estate we would probably want to have some notion of location. The definition of the district is deliberately non-specific and could refer to a school district, congressional district, a legislative district, or whatever might be useful.

Generally, we would not want to put something like the home price and the location into a single array. In this case, we have done it to give a better idea of what is possible in a for-loop.

Here, we describe the flow of the for-loop to better illustrate how execution works. First, the indices i and j are initialized. Then, the conditional is checked before we enter the loop; note that this conditional acts like a while-loop and not like a do-while loop.

Once we are inside the loop, we perform the instructions inside the braces. In this example, there is a single statement, which prints the home prices and the location of the house. After the loop internals are executed, the update is performed: incrementing i and j, and then the conditional is checked: i < 4. If the condition is true, the loop continues to run.

Finally, you may see loops written without braces, particularly in legacy code. When no braces are present, the loop contains only the next line—up to the next semi-colon. Such usage is generally frowned upon these days since it is prone to errors. The nested loops shown here, though typical, are not pleasant to read and are much worse to maintain and debug.