The basics of programming in c++ for beginners

Increment and decrement in C ++

At previous article we are considered binary operators, which is used for arithmetic operations on two operands (variables). In this lesson we will learn how to apply the unary operators, that require one operand. they are called increment ( ++ ) and decrement (). The role of these operators in, in order to change (increase or decrease, respectively,) the value of a variable by one, and the value will be overwritten. Consider the example, which will change the value of a variable variable unit in three different ways:

After each operation in lines 11, 13 and 15. to the variable variable increased by one. As you can see, the shortest recording – a record with the increment. Below, in strings 17 – 19, We have applied three times decrement and eventually obtain the value variable reduced to 3.

Compile:

increment and decrement

Both unary operator can have two forms: postfix ( where the operator is located just behind the variable) and prefix (the operator is located in front of the variable). In this example, we used postfix increment and decrement. What is the difference between these forms from each other? Both the first and second forms of these operators perform the same role – increase or decrease of a variable by one. But if a line of code, where the increment or decrement is applied, present any further commands, whereas these operators in different ways behave. Postfix will be used after the other teams. Let's look at the following example,:

As a result of lines of code 12, we will see on the screen the number of 0. It happens because, that the increase in the unit will run after the withdrawal value of the variable variable the screen. To make sure, that the value really changed – in string 13 please show us variable. But in the case of the prefix form of increment (string 16), Variable overwritten directly and already only then will display. To decrement all the same, but with a reduction unit.

Compile:

increment and decrement

Here's a look at this example more:

Result:
increment and decrement

Try to understand, why as a result of a string of operations 11, variable a It became equal 10. Asking questions in the comments not prohibited.

81 thoughts on “Increment and decrement in C ++

  1. Help me understand the problem:
    x = y = 0;
    while ( Y < 10 ) x += ++ Y;
    printf (" x= %d y = %d\n", x, Y);

    Answer x = 55 y = 10
    I don't understand how x comes out 55. I just broke my head(((

    1. x=0+1=1
      x=1+2=3
      x=3+3=6
      x=6+4=10
      x=10+5=15
      x=15+6=21
      x=21+7=28
      x=28+8=36
      x=36+9=45
      x=45+10=55

      pervaya cifra eto zna4enie x a vtoraya cifra eto zna4enie y, vote in results, ++y srazu uveli4ivaet zna4enie y na 1

  2. x=0+1=1
    x=1+2=3
    x=3+3=6
    x=6+4=10
    x=10+5=15
    x=15+6=21
    x=21+7=28
    x=28+8=36
    x=36+9=45
    x=45+10=55

    pervaya cifra eto zna4enie x a vtoraya cifra eto zna4enie y, vote in results, ++y srazu uveli4ivaet zna4enie y na 1

  3. By the way, why does it turn out to be a number? 10 , in string 11 ?? I'm using CodeBlock as my environment. First I wrote the code itself, received 9. Then I specially copied yours and … again 9. I understand so, that in the process of calculation,when the second increment is processed, it is further multiplied by 2, and only after that it adds up to the left side of the team. Can you explain?, why is that ? Or that's how it should be ? Then why do you 10? And in general, The algorithm seems a little illogical…

    1. a=++variable + 1 + ++variable*2;
      a=(2+1+3)*2; \\ I understand everything correctly?

      Then it turns out 12))

  4. I don't understand! If you count correctly, it should work 7, as – 2+1+2*2 = 7.
    But 10 turn out to be, if the compiler accepted the values (2+1+2) as in parentheses, why he took it that way is not clear and how to write, so as not to perceive it that way!?
    But most of all I don’t understand – Why does the online compiler work at all? 9!? – I don’t even understand how he thought that! Can someone explain?

  5. So, I understand now, that the second increment also increases – but then in the online compiler it is correct – 9, but why 10 – it's not clear!?

  6. I.e, на сколько я понял, компилятор сначала вычисляет variable.
    1. variable=1+1, присвоено 2.
    2. variable=2+1, присвоено 3.
    Теперь вычисляется а=3+1+3×2=10. So?

    1. точно не считал попрограммированию”, но как и считал 9 должно должно получитьсятак понялкак и в компилляторетут может опечатка или что-то вроде того….

      1. Проверил в 2-х онлайн компиляторах, та же петрушка, a=9. Но по идее должно быть 10,т.к приоритет у пре-инкремента 3 RL, а по сему сначала variable вычисляется, а потом уже он принимает участие в примере. И он по-любому равен 3, значит пример должен выглядеть так: а=3+1+3*2. Компиляторы же , apparently, считают последовательно, i.e.. а=2+1+3*2, тогда действительно получается 9. Но почему так?! Я что-то не допонял? Эх, кто бы объяснил подоходчивей.

  7. 2+1+2*2
    второй variable все еще хранит значение 1, в тот момент когда первый variable уже 2. но вот арифметика мне пока непонятна. умножение то должно выполняться первым.

Leave a Reply

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