Evgenii Legotckoi
Evgenii LegotckoiJune 9, 2017, 4:37 p.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
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 8, 2024, 3:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 7:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 5:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 6:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 8:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 5:57 a.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 1:18 a.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 3:48 a.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks