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
AD

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

  • Result:50points,
  • Rating points-4
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
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 11:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks