The loops while and do while in C ++




цикл while и цикл do while

We have already considered one of the repetition structures in C ++ – for loop. In this article, I'll look at two loops: while and do while. They are very similar to each other. Their syntax:

цикл while в C++
Fig.1 – syntax while
цикл do while в C++
Fig.2 – syntax do while

The only difference is that, that at the beginning of the loop while, the conditional test occurs immediately. If it returns false (false), the body of the loop does not execute even once. And when using do while, immediately execute operator(-s) in the loop, and then it will check the condition in parentheses ( ) after the keyword while. And similarly, when returning false, loop shuts down, otherwise – runs the next step (iteration). That is, body of the loop do while executed at least once, in any case.

Let's talk about them separately. Let's start with the while. As mentioned above, to perform body of the loop , need to check if the conditions in parentheses ( ), it was returned to the truth (true). Check the conditions and performance of the body will occur, until the condition will return false. From this comes out, that to break the loop, his body anything should occur, that will affect the test conditions. This may be either entered by the user from the keyboard variable, which is present in the test loop provided. Or it may be an increase or decrease of the manipulated variable, which is also involved in the test condition. Consider the case of changing the value of the manipulated variable in the loop. Formulation of the task: the user wishes to refill the card account through the terminal. He enters the amount from the keyboard. Provide the ability to change the program mistakenly entered the amount.

The control variable exit declares and initializes the unit to loop while – string 9. Therefore, when the loop, check conditions while (exit == 1) return true (More details about this can be read read here) and you will be taken to implement the loop body. This condition is often written in such a way: while (exit). With such a condition of the program works, as with the previous. The reason is, that any variable exit than zero will be treated by the compiler, how true. The body of the loop will be executed, until the user changes the value of this variable at 0. Then while (exit) It would be tantamount to while (0). That is, the verification condition is false. This record is more common, because it is shorter, although not so clear, how and, in the example that. For this you just have to get used.

In strings 16 – 17 the user is asked and offered to make a choice: cout << “Pay and get out – press 0. Change amount – press 1: “; That is, if he made a mistake when entering the replenishment, he has the opportunity to correct it, clicking 1. Once the user enters the correct amount and clicks 0 (that corresponds to the “Pay and get out”), exit the loop occurs and the program will continue to work. As a result, the screen will display a message on the amount of deposit – strings 20 – 22.

Result:

цикл while в C++

The same task can be accomplished using a loop do while. In this case, initial value of the variable exit It can be anything. Loop in any case carry out the body and offer to make a choice. Look:

Executing the program, see, that despite the fact, that the variable exit initially equal 0, loop body do while executed. This is because, that verification of the conditions below is the body – in string 18. Note the semicolon ; after the closing parenthesis. For the loop do while it is obligatory.

Comparing loops for, while and do while it is seen, what they look like. Only in the loop for all necessary for its normal operation assembled on the same line (declaration and initialization of the control variable, verification condition, changes in the control variable). Whereas, in loops while and do while the control variable is declared before the loop, and its change occurs later in the body. What kind of design use of repetition – you decide. Most loops while and do while then apply, when initially unknown, how many repetitions will (as in our example). It should still be remembered, that unlike the loops while and do while , control variable of loop for not visible outside its body (that is, when the output of the loop, she is destroyed).

We also offer the same training video on the theme of loops in C ++. As it considered the loop for:

Leave your questions in the comments. If possible, share the article with your friends on social networks. Tasks on the subject already have!

Newsletter of programming:

The loops while and do while in C ++
4.5 (90%) 2 votes

8 thoughts on “The loops while and do while in C ++

  1. I've decided so the first task. Is it possible to somehow simplify the code?

    #include
    using namespace std;

    int main()
    {
    setlocale(LC_ALL, “rus”);

    int amount = 0;
    int sum = 0;
    int number;

    do
    {
    cin >> number;
    sum += number;
    amount++;

    } while (number != 0);
    cout << endl;
    amount–;
    cout << amount << endl;
    cout << sum << endl;
    cout << sum / amount<< endl;

    return 0;
    }

  2. #include
    #include
    using namespace std;// reduction type (cout<>)

    int main()
    {
    setlocale(LC_ALL, “rus”);// inclusion of Russian language
    int summa = 0;
    int kol_vo = 0;
    int chislo = 0;
    int a ;

    while(a > 0)
    {

    cout <> a;
    chislo = chislo + a;
    summa = chislo + a;
    ++kol_vo;

    }
    kol_vo = kol_vo-1;
    cout << "колличество вводов:" << kol_vo << endl;
    cout << "Сумма введенных чисел:" << sum << endl;
    cout << "соеднее введеных чисел:" << summa / kol_vo << endl;

    getch ();
    return 0;
    }

  3. Guys, у меня программа зацикливается на месте
    (You are welcome, введите только \у\или \n\”)
    Не подскажите, what's my mistake?

    1. excuse me, код скопировался не совсем верно.

      1. И снова, кхм.
        #include
        using namespace std;

        int main()
        {
        setlocale (LC_ALL,”rus”);
        int number = 0;
        char answer = ‘y’;

        while (answer == ‘y’)
        {
        cout <> number;
        cout << number << " в квадрате равно " << number * number << endl;
        cout <> answer;

        if (!(answer = ‘y’) || (answer = ‘n’))
        {
        while ((answer != 'And') || (answer != ‘n’))
        {
        cout <> answer;
        }
        }
        }
        return 0;
        }

Leave a Reply

Your email address will not be published. Required fields are marked *