Increment and Decrement Operators Revisited

  1. The increment operator ++ and decrement operator --can be used to increase or decrease an integer-valued variable by one.

  2. These operators may be used by writing them as either a prefix or a postfix to the variable.

  3. For example, if n is an integer variable then one can write:

    ++n // prefix
    --n // prefix
    n++ // postfix
    n-- // postfix

  4. When the prefix version of these operators are used, the increment or decrement takes place first and then the new value of the variable is used as prescribed.
    When the postfix version of these operators are used, the increment or decrement takes place only after the value of the variable is used as prescribed.

  5. For example, the code:

    int number = 2;
    int value_produced = 2*(++number);
    cout << value_produced << endl;
    cout << number << endl;

    will produce the output:

    6
    3

    because the number is incremented by 1 before it is multiplied by 2.

    However, if we replace ++number by number++, the code:

    int number = 2;
    int value_produced = 2*(number++);
    cout << value_produced << endl;
    cout << number << endl;

    will produce the output:

    4
    3

    because the number is incremented by 1 only after it is multiplied by 2.

  6. What will the following code produce?

    int n = 3;
    cout << "Value of n is: " << n << endl;
    cout << "Value of n++ is: " << n++ << endl;
    cout << "Value of --n is: " << --n << endl;
    cout << "Value of n is: " << n << endl;

    The answer is:

    Value of n is 3
    Value of n++ is 3
    Value of --n is 3
    value of n is 3

  7. //Calorie-counting program.
    #include <iostream>
    using namespace std;

    int main( )
    {
        int number_of_items, count, calories_for_item, total_calories;

        cout << "How many items did you eat today? ";
        cin >> number_of_items;

        total_calories = 0;
        count = 1;
        cout << "Enter the number of calories in each of the\n"
                << number_of_items << " items eaten:\n";

        while (count++ <= number_of_items)
        {
            cin >> calories_for_item;
            total_calories += calories_for_item;
        }

        cout << "Total calories eaten today = " << total_calories << endl;
        return 0;
    }