The for loop in C++

for C++, for С++

As you can see in content, on the home page, in C ++ language used several types of loops. Loop for we look at the first, since it is easier to understand for beginners, from my point of view. And loops while and do while, reviewed in a separate article.

For the beginning, Let's deal with those, means that the loop programming. The loop is a special statement, by which there is a repetition of a certain section of code a certain number of times (a piece of code and repeat the loop must be interrupted - defines the programmer). Another definition proposed visitor to our site rrrFer: loop – language construct, which allows you to re-execute commands. For example, to display the numbers from one to five hundred, you can use the manual display:

ручной ввод (без цикла for)

Agree – not the most interesting reference and imagine how much would have to scroll the mouse wheel, to get to the end of the code. And you can use the loop for and cut, thus ten times, time to write this “interesting” programme and sheer size code. Here is, how to perform this task with for:

We begin to define our loop in a row 6 . To do this, we write the keyword for and behind him parentheses () . In parentheses is declared to the control variable (the variable counter) i. In our case, It is initialized to zero. After initialization, a semicolon ; . Next, we have the condition: i < 500 (it means, that is i less 500, the code in the body of the loop will be repeated) and again a semicolon ; . That it will be “speak” program how long will run the loop body (the code in curly braces {}). finally indicate, how it will change i with each loop step (in the us – increase per unit, using postfix increment). If you describe in one sentence, then, that is located in brackets, the command will sound so – execute the loop body, while the variable i less than five hundred, increasing i per unit, at each step of the loop. Step of loop is called iteration. A variable counter – a control variable, because it controls the number of iterations.

Let us consider, for clarity, a few steps from the loop of our example. The first iteration of the loop control variable is 0. Therefore, to display units using the expression i + 1 (0 + 1). When the loop body is made, change occurs (increase) a control variable i so, As we indicated in parentheses () after the operator for – that is, it is unity. The second iteration starts with testing conditions (in the us i < 500). If i really < 500, the loop body again – the screen will appear again i + 1, that is equivalent to 1 + 1, then there are 2. Last time the loop is executed, when the control variable is equal to 499 and the screen will show the value i + 1 (499 + 1). Then again, its value is increased by one, but the condition of repetition loop will not be executed, as i (500) already not less 500. After completing the loop, the program will move to the next line of code execution, located behind the cover } brace of the loop body. The result of the execution of the programme see for yourself, running the program.

The control variable can either increase or decrease. Depending on, what is the task before a programmer. Look at this code. When it is running, on the screen, we see the number of, located Descending, from 500 to 1.

It is not necessary to use a postfix increment or decrement. Change the control variable so, as required by the task. This can be ++i, i = 2, i = 20, i -= 15… For example:

цикл for - управляющая переменная

the control variable i It varies between 8 to 88 inclusive, while a step change is 8. That is, first i = 8, on the second iteration, 16 and so on up to 88.

цикл for - управляющая переменная

the control variable i It varies between 3000 to 300 inclusive, with decreasing at each iteration 300 (3000, 2700, 2400…)

цикл for c++, цикл for c++

the control variable i It varies between 0 to 100 inclusive, with an increase at each iteration 10. (0, 10, 20…100)

цикл for - управляющая переменная

the control variable i It varies between 3000 to 3 inclusive, division at each iteration 10. (3000, 300, 30, 3)

In addition to all the above, i want to add, that all three, used in parentheses, expressions are optional. If you do this, for example, record: for( ; ; ) – it will be perceived by the compiler, as the launch of the so-called infinite loop. There is not a control variable, no condition to continue the loop, no change of the manipulated variable. That is, the loop will run indefinitely. In this case, to still somehow work with such a loop, the control variable can be determined before the loop, its change can be added to the end of the body for, and the continuation of the loop condition can be set using the operator if and operator break. Here's how it will look:

I note, that there is such a thing, as the scope of a variable. In this example, the variable scope i – the body of the main function main(). In the previous examples, It was limited to the body of the loop for and its chapels, this variable was already available (to it could no longer be contacting – display its value on the screen, for example) It should be borne in mind. So as, if the program found several loops and control variables are defined in the code above, not in parentheses () after operators for , for each need to come up with a unique name. Or in some other way out of this situation. So it is better to use the standard syntax:

for ( definition of the control variable ; loop repetition condition ; changes in the control variable )

Since the code is easier to read, everything you need to run the loop is within one line of code and how many there would be no cycles in your code, you do not have to bother and come up with new names for the control variables.

I recommend to watch videos on the topic. It reviewed and while loop

Programming practices on this topic is here – Tasks: The for loop.

Newsletter of programming:

The for loop in C++
5 (100%) 5 votes

38 thoughts on “The for loop in C++

  1. admin, thank you for writing such articles legible. Write on and do not listen to anyone. I love you as a beginner very well understand programming!

    1. Vitali, Thank you ) Therein are – to understand basic simple examples. And for deeper understanding – there's no good books and practice anyone can not do.

      1. Incidentally, I note, finding site for the beginner. I shoveled a hundred resources. I saw the writing style and then rubbed the rest of bookmarks.

      2. thank you very much! We look forward to new lessons. In particular the work with files. Very important issue. thanks again!!!! Author cool, really helps out!

  2. thank you, author!
    Are you one of those people, by which, much is made available in the development of IT technologies in education and human development, and it is very cool case and a cool contribution.

  3. Hello. Explain, please, why in the first task condition
    cout << i + 1 It is only performed for the first time, and then ignored?

      1. but then where does i ++ , because this team must also add one ? i.e.. сначала cost << 0+1 = 1, displays 1,
        then i ++ action is performed and another unit is added 1 + 1 = 2,

        2 < 500? less,

        тогда cost << i + 1, i.e.. 2+1= 3, and the screen should be displayed 3, but not 2.
        where the catch? без этого "i+1" all perfectly logical turns.
        thank you in advance.

      2. Obtained should not “perfectly logical”, and checking the operation code!

        Оператор cost << i + 1 – nothing and did not increase: as the value of i 0 before surgery, will remain 0 after.
        And even cout << i + 1000000 in no way It will not change the value of i.
        cout – it just outputs the calculated the value of the, and variable i no assignment there is not shown.

  4. If I am not mistaken admin at the beginning of writing – “more practice”. I braked himself with it “i+1”, and then to practice and become clearer.
    That is. More CODE(practicing) and we will be clearer.

  5. Объясните мне кто нибудь почему у меня компилятор считает с 299, а не с 500 ?
    using namespace std;

    int main()
    for (int i = 500; i > 0; i–)
    cout << i << endl;

    return 0;

    1. Ни iни i-1 одна и таже чушь, цикл продолжает считать на уменьшение, but 299 в чем прикол не пойму.

      1. У меня в CodeBlocks было тоже самое, если выводить в столбик.
        Но если выводить в строчку, то все нормально:

        using namespace std;
        int main()
        for (int i = 1; i < 500; i )
        cout << i << " ";
        return 0;

Leave a Reply

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