There are two loop constructs in C++. One of them is the while loop and I’ll cover it in a separate article. The other loop construct, and the one I want to discuss in this article, is the for loop.

The for loop is used when you want to iterate, or loop over, a set of statements, a specific number of times. If you are processing the elements of a container, such as an array or a vector, you will want to use a for loop. If you are processing 10 pieces of data received from the program user, you will want to use a for loop.

Examples of situations where you don’t want to use a for loop are when you are processing the data in a file and you don’t know how many pieces of data are in the file or if you are processing data from a user and you don’t know how many data elements will be entered.

for Loops Types

There are two types of for loops. The first type I’ll call variable-controlled. This means that in the for loop you initialize a variable and the value of that variable determines how many times the for loop iterates.

The other type of for loop is a range for loop. This type of for loop iterates over all the elements of a container, such as a vector or an array. You use this type of loop when you want to process every element of a container, starting with the first element and continuing to the last element. Using a range for loop stops any type of logical error you may get from trying to access an element that is beyond the bounds of the container.

The Variable-Controlled for Loop

The most common for loop type is the variable-controlled for loop. A variable is initialized inside the body of the loop to control the number of loop iterations. I’ll call this the loop control variable. You can initialize the loop control variable outside the loop body but then the scope of the variable is not local to the loop, which you probably don’t want.

Here is a syntax template that defines the structure of a variable-controlled for loop:

for (variable-init; condition; variable-modification) {

loop-body;

}

There are four parts to a for loop: 1) the variable initialization, where you assign a value to a variable to control the loop (the loop control variable); 2) the condition you are testing for to stop the loop; 3) the variable modification, where you modify the value of the loop control variable so the condition eventually is true; and 4) the loop body — where the work of the loop is performed.

#coding-tips #programming-tips #learn-to-program #learn-to-code #cplusplus #programming-c

Learning C++: for Loops
1.20 GEEK