Last Updated:

C++ - Loops for, while, do.. while

Loops are extremely important in C++ programming, and indeed in other languages. Let's start with the theory.

A loop is the repetition of the same piece of code in a program. The sequence of actions that are repeated is called the body of the cycle. One pass of the cycle is a step or iteration. Variables that change within a loop and affect its ending are called loop parameters.

C++ provides three operators that implement a cyclic process: whiledo.. while and for. Let's look at each of them.

Statement with precondition (while)

Here's how it works. The value of the expression is evaluatedIf it is true, then the operator is executed. Otherwise, the cycle ends. If it consists of more than one statement, you must use a composite operator:

while condition


Let's look at an example. Let us create a program that, depending on the age of the user, determines how many years he has left before retirement. Provided that the retirement age is 56 years.

Here is the result of the program:


Loop with postcondition (do... while)

Sometimes there is a need for the body of the cycle to be executed at least once, but the condition does not allow this to happen. This is where the loop with the postcondition do... while. Which is implemented by the following design:

do operator while (expression);

The loop works as follows. An operator is executed first, and then the value of the expression is evaluatedIf it is true, the loop body operator is executed again.

Let's consider the code on the example of the previous program, changing some lines.


Loop with parameter (for)

This cycle can be represented by such a construction;

for (initial assignments; expression, increment) operator;

Here, initial_assignments are an operator or group of operators used to assign initial values to values used in a loop; expression — defines the condition for executing a loop, if it is true, then the loop is executed; increment — an operator that is executed after each step (pass) along the body of the cycle; operator — any operator.

Let's look at a loop with a parameter using an example of a task. We need to calculate the sum of numbers from 1 to 500. Do:

The answer is 125250.