Evgenii Legotckoi
Evgenii LegotckoiJune 9, 2017, 6:37 a.m.

C++ - Tutorial 004. Tests and loops

C++ provides a standard set of operators for selecting a selection and cycles.

The keywords related to the construction of branching conditions for the code are:

  • if
  • else
  • switch
  • case
  • break
  • default

The key words relating to the construction of cycles are:

  • do
  • while
  • break
  • continue
  • for

Condition statements

The If statement

The condition construct using the if statement is formed as follows:

int x = 56;

bool check_x()
{
    if (x > 0)
        return true;
    return false;
}  

In this case, the condition is placed in parentheses after the if statement. In this construction, the return code is true; Will be executed if x is greater than 0. next line return false; No longer applies to the code that will be executed when the condition is met. In condition constructs, if this condition is met, only one line of code will be executed if the code is not enclosed in curly brackets, that is, if the body of the code executed on condition is not formed. Let's consider two variants of the code:

First option:

int x = 56;

bool check_x()
{
    if (x > 0)
        x = 0;
        return true;
    return false;
}  

In this code, return true; Will always be executed, because only the string x = 0 is relevant to the code being executed;

Second option:

int x = 56;

bool check_x()
{
    if (x > 0)
    {
        x = 0;
        return true;
    }
    return false;
}  

In this code, return true; Will be satisfied only if the condition x> 0 is satisfied.

The else statement

The else statement is used in conjunction with the if statement to form a sequence of conditions.

int x = 56;

bool check_x()
{
    if (x > 0)
    {
        x = 0;
        return true;
    }
    else if (x < 0)
    {
        x = 0;
        return false;
    }
    else
    {
        return false;
    }
}

The else statement can be used to add a new condition if the previous condition, else if statement, fails. And as a final code in a sequence of conditions, if the previous conditions were not met. Alternatively, it is possible to use the braces for the code body if the code fits in one line.

Statements switch, case, break, default

The switch case construct is used to select the branching of the code, in the condition of which the choice is made by integer values. This means that the switch case can be used for just integer values, enumerations, and selections by the symbol code.

int x = 100;

bool check_x()
{
    switch (x)  
    {
        case 0:
            return true;
        case 50:
            x = 0:
            break;
        case 100:
            return false;
        default:
            return false;
    }

In the above code, the variable x is checked to be equal to the numbers 0, 50, 100. The default operator selects the code that is executed if none of the conditions are met. Note also that in the code block with case 50: added a break statement, this statement exits the condition, while the return statement exits the function. If you do not add a break statement, the code execution will continue in case 100:. Due to this peculiarity of switch case construction, it is possible to combine conditions for which it is necessary to execute the same code. For example:

int x = 100;

bool check_x()
{
    switch (x)  
    {
        case 0:
        case 50:
        case 100:
            return true;
        default:
            return false;
    }
}

Thus, for x equal to 0, 50, 100, the function returns true, while for all other values the function returns false.

Also, the code for selecting case in this construct can be wrapped in blocks of code, which will limit the scope and use declarations of variables with the same name.

int x = 100;

int check_x()
{
    switch (x)  
    {
        case 0:
        {
            int y = 1;
            return y;
        }
        case 50:
        {
            int y = 2;
            return y;
        }
        case 100:
        {
            int y = 3;
            return y;
        }
        default:
            return x;
    }
}

Thus, by restricting the scope, we are able to use variables with the same names in case conditions. But do not forget that outside the scope, bounded by curly brackets, the variable y will not exist in this case.

Cycle operators

The while statement

The while statement repeats the code in its body as long as the condition is met. For example:

int i = 0;

while (i < 10)
{
    i = i + 1;
}

In this code i will be 10 after the loop.

The do statement

The do statement is used in conjunction with the while statement and allows the loop body to be executed at least once, before the loop condition is checked. For example:

int i = 15;

do
{
    i = i - 5;
    std::cout << i << std::endl;
}
while (i > 0  && i < 13);

In this code, the variable I does not initially match the condition and in the usual while loop the body code of the loop has not been executed, but since the do-while loop is used, the test will be performed after the loop body is executed. As a result, the output of std :: cout is:

10
5
0

You can ask, why is there 0 in the output? It does not fit the condition. Again, due to the fact that the check is performed after the code is executed in the body of the loop. That is, the body of the loop has been executed, and then a check is performed, the result of which the cycle completes its work.

The break statement

As in switch case, this statement can be used in loops. This is necessary in order to exit the loop, before the cycle condition is fulfilled. For example:

int i = 15;

while (i < 50)
{
    if (i < 0)
    {
        break;
    }
    i = i - 5;
}

In this artificial example, an eternal cycle would result because the variable i decreases instead of increasing, and by the condition of the loop, the output will be produced only if i is greater than 50. But thanks to the break statement and the test condition for the negative value of the variable i The execution of the program will exit this loop as soon as i becomes less than 0.

The continue statement

This operator allows you to abort the iteration of a loop and start a new iteration of the loop before executing all the code in the body of the loop. For example:

int i = 0;

while (i < 5)
{
    if (i == 3)
    {
        i = i + 1;
        continue;
    }

    std::cout << i << std::endl;
    i = i + 1;
}

When executing this code, we get the following output:

0
1
2
4

That is, the output of number 3 will be omitted.

The for statement

Loops with the for statement allow you to combine the initialization of variables, the condition and the change of these variables.

That is, the following while loop

int i = 0;

while (i < 10)
{

It will be equivalent to the following for loop:

for (int i = 0; i < 10; i++)
{
    // ToDo Something
}

The advantage of this for loop will be that the variable I will be in the local scope of the for loop.

For loops can be initialized with several variables of the same type. For example:

for (int i = 0, *p = &i; i < 9; i += 2) {
    std::cout << i << ':' << *p << ' ';
}

Also, the condition can be declaration, initialization of a variable. For example:

char cstr[] = "Hello";
for (int n = 0; char c = cstr[n]; ++n) {
    std::cout << c;
}

Given the C ++ standard 11, the auto variable can be used as the variable type, which allows you to output the type of the variable from the initializer:

std::vector<int> v = {3, 1, 4, 1, 5, 9};
for (auto iter = v.begin(); iter != v.end(); ++iter) {
    std::cout << *iter << ' ';
}

Also an interesting point is that the initializer, condition and block of change can be the expression:

int n = 0;
for (std::cout << "Loop start\n";
     std::cout << "Loop test\n";
     std::cout << "Iteration " << ++n << '\n')
{
    if(n > 1)
        break;
}

Beginning with the C ++ 11 standard, for loops, iteration has been added for containers that support iteration. For example, the vector container from the standard library:

std::vector<int> v = {0, 1, 2, 3, 4, 5};

for (const int& i : v) 
    std::cout << i << ' ';

In this code, the loop construction is as follows:

for (Retrieved from the container at each iteration of the object : container)
{
    // Body of the cycle
}

Also, Range-based for loops support the auto statement. For example:

std::vector<int> v = {0, 1, 2, 3, 4, 5};

for (auto& i : v) 
    std::cout << i << ' ';
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10

C++ - Тест 003. Условия и циклы

  • Result:42points,
  • Rating points-8
Last comments
i
innorwallNov. 9, 2024, 2:43 a.m.
Release of C++/Qt and QML application deployment utility CQtDeployer v1.4.0 (Binary Box) can i buy priligy in usa Reprod Biomed Online 10 3 310 319
i
innorwallNov. 9, 2024, 2:29 a.m.
EVILEG - 4 Years Online buy priligy Pelleted food this way of administration is less stressful for the mice, and a few vendors offer a commercially available chow
i
innorwallNov. 8, 2024, 7:51 p.m.
Django - Tutorial 036. How to add authentication through social networks. VKontakte buy priligy online usa In addition, it might not be effective at the doses recommended, because of your previous tolerance to a similar type of drug
i
innorwallNov. 8, 2024, 6:40 p.m.
Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column? priligy results This slowing of eGFR decline was observed in patients with and without low eGFR and in those with and without type 2 diabetes
i
innorwallNov. 8, 2024, 1:45 p.m.
QML - Lesson 002. Custom Button in QML Android 2007; 14 2 270 83 priligy dapoxetine 60mg Testicular imaging is sort of a unique niche right now, Гў
Now discuss on the forum
i
innorwallNov. 8, 2024, 6:08 p.m.
добавить qlineseries в функции School of Nursing, Long Island University, Brooklyn Campus, Brooklyn, NY, USA priligy dapoxetine 30mg
9
9AnonimOct. 25, 2024, 7:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…
F
FynjyJuly 22, 2024, 2:15 p.m.
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Follow us in social networks