The for loop in C++

The for loop in C++
5 (100%) 1 vote

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:

34 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. Благодарю покорно! Ждем новых уроков. В частности о работе с фалами. Очень важная тема. Спасибо еще раз!!!! Автор крут, реально выручаешь!

  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. объясните пожалуйста, почему в первой задаче условие
    cout << i + 1 выполняется только первый раз, а дальше игнорируется?

    1. Кто сказал что дальше игнорируется?
      Этот оператор cout << i + 1 executed 500 times.

      1. но тогда куда девается i++ , ведь эта команда тоже должна прибавить единицу ? i.e.. сначала cout << 0+1 = 1, displays 1,
        потом выполняется действие i++ и прибавляется еще единица 1+1=2,

        2 < 500? less,

        тогда cout << i + 1, i.e.. 2+1=3 и на экран должно выводиться 3, but not 2.
        где подвох? без этого "i+1" все прекрасно логически получается.
        заранее спасибо.

      2. Получаться должно непрекрасно логически”, а проверкой работы кода!

        Оператор cout << i + 1 – nothing и никак не увеличивает: как было i значением 0 до операции, так и останется 0 after.
        И даже cout << i + 1000000 никак не изменит значения i.
        cout – это только вывод вычисленного the value of the, а переменной i никакого присвоения там не показано.

Leave a Reply

Place code in tags: <pre class="lang:c++ decode:true ">YOUR CODE</pre>