Learning C++

Looping

For tasks with fixed cycles or where instructions should continue until something occurs, there is a programming terminology a concept called looping.

In C++, two of the most common looping structures are the for and while loops.

For

The for loop consists of four parts: the initial statement, the conditional statement, the contents, and the end statement.

Initial Statement

Very often, the initial statement of a for loop will set the first value. Because for loops run in fixed cycles, this first value will often be 0 or the maximum when counting down.

Conditional Statement

At the beginning of each loop, the for loop will check the conditional statement. If it is still true, the loop will continue. If not, the loop will end.

Contents

Each loop, the contents of the loop will be run.

End Statement

At the end of the loop, the end statement will be run. Usually, but not always, this either increases or decreases some counter.

While

The while statement works like a conditional statement. It will continue to loop until the condition is no longer true within it.

Like a for loop, the while loop will run its contents each time. However, unlike the for loop, the while loop does not have an end statement. Any changes to complete the looping must happen inside the contents of the loop.