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. does not pass the correct answer ,prompt ,I can't find the error: #include
    using namespace std;
    int main()
    {
    setlocale(LC_ALL, “rus”);
    int digit1 = 0;//user enters numbers
    int digit2 = 0;//user enters
    int result = 0;//the variable stores the result of the multiplication

    cout << "Введите два однозначных числа : " <> digit1;
    cin >> digit2;
    cout << " digit1 * digit2 = result : " << digit1 * digit2 << endl;
    system("cls");
    int answer = 0;
    cout << answer ;//the result of multiplication is guessed by the user
    cout << "Угадайте результат умножения введенных вами двух чисел : " << endl;
    cout << "Вариант ответа в пределах (from 1 to 81)" << endl;
    for(result = 1; result > answer;
    cout << result < result)
    {
    cout << "Вы дали неправильный ответ! your other option : ";
    }
    else if(answer < result)
    {
    cout << "Ваш ответ неверный , other options : " << endl;
    }
    else
    {
    answer == result;
    break;
    cout << "Правильный вариант ответа!" << endl;
    }

    }

    return 0;

    1. Here is the code:
      #include
      using namespace std;
      int main()
      {
      setlocale(LC_ALL, “ru”);

      int digit1 = 0;
      int digit2 = 0;
      int result = 0;
      int answer;

      cout << "Введите два однозначных числа : " digit1;
      cin>> digit2;
      if (digit1 >= 10 || digit2 >= 10) //IF either of the two specified variables is greater than 10 or even 10 the program will complete its work. || OR
      {
      cout << "Вы ввели не однозначное число." << endl;
      return 0;
      }

      else
      {
      result = digit1 * digit2;// We multiply the numbers that we entered and assign them to the result variable;
      system("cls");
      cout << "Угадайте результат умножения введенных вами двух чисел : " << endl;

      cout << "Вариант ответа в пределах (from 1 to 81)" answer;
      if (!(answer == result)) // IF answer is NOT equal to result
      {
      cout << "К сожалению ответ неверный, correct answer: " << result << endl;
      }
      else
      {
      cout << "Вы молодец! you guessed the number" << endl;
      }
      }
      }

  2. Here is the code:
    #include
    using namespace std;
    int main()
    {
    setlocale(LC_ALL, “ru”);

    int digit1 = 0;
    int digit2 = 0;
    int result = 0;
    int answer;

    cout << "Введите два однозначных числа : " <> digit1;
    cin>> digit2;
    if (digit1 >= 10 || digit2 >= 10) //IF either of the two specified variables is greater than 10 or even 10 the program will complete its work. || OR
    {
    cout << "Вы ввели не однозначное число." << endl;
    return 0;
    }

    else
    {
    result = digit1 * digit2;// We multiply the numbers that we entered and assign them to the result variable;
    system("cls");
    cout << "Угадайте результат умножения введенных вами двух чисел : " << endl;

    cout << "Вариант ответа в пределах (from 1 to 81)" <> answer;
    if (!(answer == result)) // IF answer is NOT equal to result
    {
    cout << "К сожалению ответ неверный, correct answer: " << result << endl;
    }
    else
    {
    cout << "Вы молодец! you guessed the number" << endl;
    }
    }
    }

  3. cout << i+1 << endl;
    as I understand the loop body starts spinning from 1
    if there is another number, then the answer will start from it

  4. int main()
    {
    int a = 0;
    int b = 0;

    cout << " mention of number " <> a;

    cout << a << endl;

    cout << endl;
    {
    for (a = 0; a < 10; a++)

    cout << a + 1 << endl;
    }

    return 0;
    }
    "for" ignoring variable after "cin" changed one ?

Leave a Reply

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