The four parts of each loop in C++

The simplest control structure in C++ is the while loop. Although it’s not completely flexible, the for loop is actually the more common of the two – it has a certain elegance that’s hard to ignore. You will notice that most episodes consist of four basic parts.
Setup: Setup usually involves declaring and initializing an increment variable. This generally happens before the period.
Test expression: The expression inside the while loop that will make the program execute the loop or exit and continue. This always occurs inside the parentheses following the while keyword.
Body: This is the code inside the parentheses.
Increment: This is where the increment variable is incremented. This usually happens at the end of the body.
In the case of the factor program, the four parts looked like this:
int nValue = 1; // the setup
while (nValue <= nTarget) // the test expression
{ // the body
cout << nAccumulator << ” * ”
<< nValue << ” equals “;
nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
nValue++; // the increment
}
The for loop incorporates these four parts into a single structure using the keyword for:
for(setup; test expression; increment)
{
body;
}
The flow is shown graphically here:
image0.jpg

1. As the CPU comes innocently upon the for keyword, control is diverted to the setup clause.
2. Once the setup has been performed, control moves over to the test expression.
3. (a) If the test expression is true, control passes to the body of the for loop.
(b) If the test expression is false, control passes to the next statement after the closed brace.
4. Once control has passed through the body of the loop, the CPU is forced to perform a U-turn back up to the increment section of the loop.
5. That done, control returns to the test expression and back to Step 3.
This for loop is completely equivalent to the following while loop:
setup;
while(test expression)
{
body;
increment;
}

Leave a Comment