The basics of programming in c++ for beginners

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 cycle. Step cycle 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 cycle 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 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 variablei  It varies between 0  to 100 inclusive, with an increase at each iteration 10. (0, 10, 20…100)

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

the control variablei  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 operatorsfor , 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.

50 thoughts on “The for loop in C++

  1. * using strange terms such as “the control variable”. I have not seen such anywhere.

    * break statement IMHO it was necessary to describe in this article, and even rename the article and then to describe the do and while loops. About the continue statement is also not forget.

    * I do not know what you're going to write it in a separate article about the break, but you have already described on the website: https://purecodecpp.com/archives/237

    * area of ​​visibility…, and that you did not touch on this topic, when branching described?
    [cpp]
    int a = 100;
    if (true) {
    int a = 50;
    ++a;
    std::cout << a; // displays 51
    }
    std::cout << a; // displays 100
    [/cpp]

  2. Vova, we must apparently be attributed to me now in front of you )))

    * term “the control variable” can be found in the book “How to program in C ++” HM. Data, P.Dzh. Deitel well and msdn site, for example

    * Article writing deliberately small. it is my right. I think, that it is better not to give at one time a lot of information

    * in an article about the break I describe and continue

    * scope is not affected, when branching described

    1. course right, I'm really against. I've yet to determine the least dokapalis:
      >> The cycle - is the repetition of a certain piece of code a certain number of times

      The definition is not correct at all. Loop (in this context) – this design, reiteration – this process. It is impossible to determine the subject through the process. Closer to life – you define(and):

      Car – transport on the roads of people and goods.

      Besides, you are writing “a number of times”. The number of times may not be determined in advance. In C ++, at least.

      But I pick and, as seen, not always successfully.

      1. Determining the cycle we modify! The head understands, and the words are sometimes difficult to properly explain.
        P.S. “correctly” – This is true, Vova to approved :)

      1. A bug in the definition seems to be a logical.

        >> In parentheses is declared to the control variable (the variable counter) i. … Step of loop is called iteration. A counter variable - control variable, because it controls the number of iterations.

        Here 2 once introduced the same concept.

        I do not know about you, and I cut my eyes Union “and” in the beginning of the sentence (I watch the full text of all articles). I also drank a lot of beer and poorly studied, but I remember, that in the beginning of the sentence it is put only in the descriptive scenes of works of art, when they want to reflect the enthusiasm (“And how about the birches and space!”). Bad poets still do that if the rhymes are not rushing. In technical texts never ever seen.

        Commas are a hit. Everywhere.
        >> If you describe in one sentence, then, that is located in brackets, team will sound like - to perform the loop body, while the variable i is less than five hundred, increasing i by one, at each step of the loop.

        “, then, what” – before “then” the comma is not needed.
        “Perform loop body for each iteration of the loop.” or “execute the loop body …, increasing at the i unit at each iteration of the loop” ?
        “death, can not be pardoned” :).

        The opening brace should be separated by a space from preceding text:
        >> if и оператор break(in about

        xD.

    1. A Th there to understand?

      global Variables, local.
      You can recall the extern (http://stackoverflow.com/questions/1787875/use-of-extern-storage-class-specifier-in-c) и static (http://msdn.microsoft.com/ru-ru/library/s1sb61xd.aspx), but better to write about them separately (there is nothing to write about, kind of).

      А так… is the operator :: to access the global scope, the rest of the field of view is limited by braces. Well, if the braces are not clearly after the for, while, if, …, they are meant.

      An example of the above seems to be komenta normally explains all, what else can write about it? In the example of a wiki is about the same: http://ru.wikipedia.org/wiki/%D0%9E%D0%B1%D0%BB%D0%B0%D1%81%D1%82%D1%8C_%D0%B2%D0%B8%D0%B4%D0%B8%D0%BC%D0%BE%D1%81%D1%82%D0%B8

      1. Do not you think that “area of ​​visibility” better to submit for consideration as a separate topic?
        I agree with you, it would have to be put at the very beginning, that would be the people who are starting to code to understand what's what!
        But here's the surprise – what did you say they say you have a lot of bad articles have been. Maybe you just do not know how to correctly choose their place and time, when a paper had to go, that would be understandable to the reader that you are coming?
        So it turns out that you yourself at one time made a lot of mistakes, which then fixes you had, and now you're so “Hero” here is advice are distributing to the author, they say it should be there, and it is for the go…
        And generally speaking, what you are soared about commas? Are you a teacher from the school?

  3. rrrFer: ” it is put only in the descriptive scenes of works of art” – Well, we will consider this article a work of art, Nor, for that matter… and comma of the problems I have always been… unless it changes something? people come here to honor those. literature, view syntax, procedures and rules of ad features, etc..
    Do not be so scrupulous… It is better to drink a beer and relax while reading the article…
    Z.Ы. since you do not like is the number of errors, why not make your own website, exactly what you want so that it had been???

    1. Duck I make my site 2011 of the year, but the trouble, with 2011 year there was not a single article and 2012 also almost all deleted. Removed article because I no longer like, were of poor quality. Now I rewrite old articles (many around the same mistakes, and that at this site), but not everyone can, or have a desire to rewrite, show the same sorts dull article I somehow dumb….

      I think, he would call someone a beer and check out my blog, and then hop – missing comma. It is all – Beer does not go, awful mood xD. Who is guilty?

      Really easy to write once without errors, than to rule. Across 2 the year you 100% I do not want to rewrite any article about if and for – it's not very interesting. Leave them too is dumb, and removal of the article is very badly perceived by the search engines. Search engine for some time gives your page in search results, and receives information, that instead of the page the user receives an error, bezpridela is to increase the percentage of failures and not only.

      In general bad article – It is the bane of any site. Have you never seen blogs with posts such as “this address is the archive – old blog, and new at the new address….”. Because it is easier to spin and a gash in the SS New Website, than re-write.

      1. Nor, for that matter, then you and seyschas many commas or skip or where necessary to put) so inappropriately here “la-la”, they say the author is not there something set, etc..
        IMHO, you'd better look for a, and the author himself will understand how and what better.
        Z.Ы. Plus you always have access – If you here a lot of things I do not like, you just can not sit on this website! is not it?

    2. Another is to share the site “new” and “archive”, with nothing removed, but to get to the bad old articles on the links to the user site can not – Only through a search engine.

      In general, one article for people, and the other for search engines. Even Habré has sandpit – I think it has a similar purpose.

      Not nice to write for search engines. Moreover, no one is sure, that the MS does not consider the average percentage of refusals Site. If you believe – the old bad articles can hang a stone around the neck site. Remove can not be (wrote above why), but a normal user logs in and almost immediately released (there is failure and perceived negatively PS- at least such rumors go).

  4. Yes, find bad article easy. bad – those, who do not like nick.
    If your site is set yandeksmetrika, then the following page, you can get all the statistics on the site.

    I have a blog now there are page, giving 11% of all website traffic (and it is not the main page, but simply Useful Article). Another gives more 7%. obviously, This quality articles. Until now, articles were giving 0.2% traffic (and the worst I generally removed). They differ as much in 50 times by this parameter. In short, you can take a number of, and the quality can be.

    IMHO, quality article contains normal administration and, the most important thing, interesting, a beautiful example. Example need to invent and think carefully.

    On the topic, I would cycle as an example of the standard took – calculation of the values ​​of some functions (y = x * x, for example) at a predetermined interval with a predetermined pitch. To program a table brought type
    1 – 1
    2 – 4
    3 – 9
    4 – 16

    Another example of…some game. type “guess the number” – the program tries to guess the number at the beginning of the game, the user tries to guess, and at each step of the program tells him “more” or “less”.
    The second example would normally show case, when the number of iterations is not known in advance. This example is very simple.

    Tabulation function x * without(x)
    [cpp]
    for (int i = 0; i < n; ++i) cout << i < ” i * without(i);
    [/cpp]

    game “guess the number”:
    [cpp]
    int val = rand() % 100, t;
    for (;;) {
    cin >> t;
    if (With t ==) {
    cout << "победа" << endl;
    break;
    }
    std::cout << (t < val ? "меньше" : "больше") << endl; } [/cpp] Не обязательно такие, можно другие примеры, главное чтобы они были красивыми, короткими и не очень скучными.

  5. >> Nor, for that matter, then you and seyschas many commas or skip or where necessary to put) so inappropriately here, "la-la", they say the author is not there something set, etc.. IMHO, you'd better look for a, and the author himself will understand how and what better.

    <> Z.Ы. Plus you always have a way out - if you're here a lot of things I do not like, you just can not sit on this website! is not it?

    << I can not sit, you are somehow associated with the administration of the site? – then sharply listen Council. Especially, I read it a second time.

    Although, IMHO, you're wrong. Comments are indexed by the search engine is not worse than the text of the article. Normal comments are very much help site.

    1. well, OK, leave “normal” comments)
      Z.Ы. I have no affiliation with the site administrator, that's where you're wrong… I'm just a reader.

    2. Comments are indexed by the search engine is not worse than the text of the article. Normal comments are very much help site.

      Yes you captain obvious) Who does not know.
      normal all. Nobody forbids you not to hang on the website, just do not clog up the wall.

  6. Dear, it seems to me, or you incorrectly written example:

    “for (int i = 1; i <= 100; i+=10)
    for loop – the manipulated variable of the control variable i varies from 1 to 100 inclusive, with an increase at each iteration 10. (1, 10, 20…)"

    In this case, the output will be: 1, 11, 21, 31..
    Or, when displaying it subtracts from the i, then the result will be: 0, 10, 20, 30…

    I am wrong?

Leave a Reply

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