C++. Cycles. Operators of the cycle ‘for’, ‘while’, ‘do … while’




Cycles. Operators of the cycle for, while, do-while


Content


Search other websites:

1. The concept of the cycle in a programming language

Often, when programming tasks, it is necessary that the same sequence of commands be executed several times. This process is called cyclic. An algorithm, in which a certain sequence of instructions is repeated several times with new input data, is called cyclic.

To implement the cyclic process, programming languages use loops. The C/C++ programming language has easy-to-use loop operators.

2. Types of cycle operators in C++

In C++, there are 3 types of loop operators:

  • ‘for’ loop;
  • ‘while’ loop with a precondition;
  • ‘do … while’ loop with a postcondition.

Each of the loop operators has its own application features. Any of the above loop statements can be replaced by another one.

3. The loop ‘for’. The general form of the cycle operator ‘for’

In C++, the ‘for’ loop can have a very wide implementation and application. The ‘for’ loop is also called a cycle with a parameter.

The general form of the ‘for’ loop statement:

for (initialization; expression; increment)
{
    // sequence of operators
    //
}

where

  • initialization – assignment operation, in which the initial value of the loop variable is set. This variable is the counter that controls the operation of the loop. The number of variables that control the ‘for’ loop can be two or more;
  • expression is a conditional expression in which the value of the loop variable is checked. At this stage, further execution of the cycle is determined;
  • increment (decrement) – determines how the value of the loop variable will change after each iteration.

The ‘for’ loop is executed until the value of the expression is true. As soon as the value of the expression is false, the loop is terminated and the statement that follows the ‘for’ loop is executed.

4. Examples of using the ‘for’ loop operator

Example 1. Find the sum of all integers from 100 to 300. A snippet of code that solves this task.

// the sum of all integers from 100 to 300
int sum;
int i;

sum = 0;
for (i = 100; i<=300; i++)
    sum = sum + i;
// sum = 40200

Example 2. The natural number n is given. Calculate the sum:

A snippet of code that solves this problem.

// s = 1 + 1/2 + 1/3 + ... + 1/n
int n;
float s = 0;
int i;

// input the value n
n = 4;

for (i = 1; i<=n; i++)
    s = s + 1.0/i;
// s = 2.08333

In this example, to get a real value, instead of the number 1 (integer type), the number 1.0 (real type) is entered. The division operation

1.0/i

gives a real result.

Example 3. Calculate the sum

A snippet of code that solves this task.

float s;
int i;

s = 0;
for (i=50; i>=1; i--)
    s = i + Math::Sqrt(s);
s = Math::Sqrt(s);
// s = 1.7579

In this example, the counter value i in the cycle is changed in descending order. This value is decreased by 1 in each iteration of the loop. When solving such tasks, the value of the loop counter must vary from the last to the first value. In this case, from 50 to 1.

In calculations, the function Sqrt() from the Math library was used.

5. What are the options for implementing the ‘for’ loop?

The ‘for’ loop can have several types of implementation. The number of variables that control the for loop can be one, two or more.

The ‘for’ loop may not contain any of the elements of the loop header:

  • initialization;
  • expression;
  • increment/decrement.

An example of a for loop operator, which has a 2 control variables. Find the values of the multiplication:

D = (1 + cos(9)) · (2 + cos(8)) · … · (9 + cos(1))

A snippet of code that solves this task.

// D = (1 + cos(9))*(2 + cos(8))* ... *(9 + cos(1))
int i, j;
float d;

d = 1;
for (i = 1, j = 9; i<=9; i++, j--)
    d = d * (i + Math::Cos(j));

In the above code snippet, two variables are used in the for loop, which change their value (i, j).

6. The while loop. General form

The while loop is called a loop with a precondition. The general form of the while loop is as follows:

while (expression)
{
    // sequence of operators
    // ...
}

where expression – any valid expression in C++. The sequence of statements is executed as long as the conditional expression returns true. As soon as the expression becomes false, execution of the while loop terminates and control is passed to the next statement.






7. Examples of using the ‘while’ loop operator

Example 1. A real number a is given. Find the smallest n, for which

Considerations. At the beginning of the value of the sum is less than the value of a. At the passage of each iteration, the value of the sum gradually increases. At some point (at some value n), this amount will be higher than the value a. This moment (the value of n) must be remembered. To compute n, the ‘while’ loop is convenient. A snippet of code that solves this task.

float a;
int n;
float sum;

// input the value a
a = 2.2;

n = 1;
sum = 1.0/n;

while (sum < a)
{
    n++;
    sum = sum + 1.0/n;
}
// n = 5; sum = 2.283334

Example 2. A natural number is given. Determine the number of digits 3 in it.

A snippet of code that solves this task.

// number of digits 3 in number
int n; // given natural number
int k; // number of digits 3 in number
int t, d; // additional variables

// input the value n
n = 12343;

t = n; // make a copy of n
k = 0;
while (t>0)
{
    d = t % 10; // select the last digit
    if (d == 3) k++;
    t = t / 10; // reduce the number of digits
}
// k = 2

In this example, the value of the original number will be divided by 10 at each iteration. Thus, the number of digits will decrease. At each iteration, using the ‘%’ C++ operation, the remainder of the division by 10 is taken, that is, the last digit of the number is determined. If this number is 3, the counter k is incremented by 1.

8. The general form of the cycle operator ‘do … while’

The ‘do … while’ loop should be used in cases where the iteration should be done at least once. Unlike ‘for’ and ‘while’ loops, in the ‘do … while’ loop, the condition is checked when the loop exits (and not when entering the loop). The ‘do … while’ loop is also called a cycle with a postcondition.

The general form of the cycle operator ‘do…while’:

do
{
    // the sequence of operators
    // ...
}
while (expression);

where

expression – conditional expression, in which the value of the loop variable is checked. At this stage, further execution of the cycle is determined. Braces in this cycle are optional.

The cycle works as follows. First, the loop body is executed. Then the value of the expression (conditional expression) is checked. If the value of the expression is true, the body of the loop is executed again. As soon as the value of the expression is false, the execution of the loop terminates.

9. Examples of using the ‘do…while’ statement

Example. Using the do … while loop, find the value of the sum:

S = 1 + 3 + … + 99

A snippet of code that solves this task.

// s = 1 + 3 + ... + 99
int t;
int s;

s = 0;
t = 1;
do
{
    s = s + t;
    t = t + 2;
}
while (t<=99);
// s = 2500

10. Nested loops. Examples of using

Nested loops can be used, for example, when working with two-dimensional (multidimensional) arrays (resetting an array, calculating sums, multiplications, etc.).

Example 1. Compute the multiplication:

D = 1 · (1 + 2) · (1 + 2 + 3) · … · (1 + 2 + … + 9)

A snippet of code that solves this task.

// D = 1 * (1+2) * (1+2+3) * ... * (1+2+...+9)
float d; // result - multiplication
int i, j; // cycle counters
int s; // additional variable

d = 1;
for (i = 1; i<=9; i++)
{
    s = 0;
    for (j = 1; j<=i; j++)
        s = s + j;
    d = d * s;
}
// d = 2.571912E+09

In this example, a ‘for’ loop with counter j is run in the ‘for’ loop with counter i.

Example 2. A two-dimensional array of integers of size 6 × 9 is given. Write 5 to all elements of the array.

int M[6][9]; // two-dimensional array of integers
int i, j;

for (i=0; i<6; i++)
    for (j=0; j<9; j++)
        M[i][j] = 5;

11. What is an infinite loop?

An infinite cycle is a cycle that never ends.

When programming cyclic processes, the programmer by mistake can write a loop code that never ends. In addition, sometimes it is necessary that the loops contain a code of special completion using the ‘break’ statement.

Example 1. Бесконечный цикл с оператором ‘for’:

for (; ;)
{
    // the sequence of operators
    // ...
}

Example 2. An infinite ‘while’ loop.

int x;
x = 5;

while (x<10)
{
    // an infinite while loop, the value of x does not increase,
    // The condition x <10 is always true, it is impossible to exit the loop
}

The above code fragment, from a logical point of view, is erroneous. Such a cycle is performed without end. Since the value of the variable x does not increase. This means that x will always be less than 10.


Related topics