Increment


Program Listing

Increment.cpp

/****************************************************************************
*                                                                           *
*   Program:    Increment                                                   *
*                                                                           *
*   Purpose:    This program demonstrates increment, decrement, and         *
*               compound assignment                                         *
*                                                                           *
****************************************************************************/

#include <iostream>
#include <string>

using namespace std;

int main() {

//  Post-increment and post-decrement

    int a = 5;
    a++;
    cout << "a = " << a << endl;
    a--;
    cout << "a = " << a << endl << endl;

//  Pre- vs. post-increment and decrement

    cout << "a = " << a++ << endl;
    cout << "a = " << ++a << endl;
    cout << "a = " << a-- << endl;
    cout << "a = " << --a << endl << endl;

//  This expression is ambiguous, but legal

    int b = a + a++;
    
    cout << "b = " << b << endl << endl;
    
//  Compound assignment

    cout << "a = " << a << endl;
    a += 2;                         // Add 2
    cout << "a = " << a << endl;
    a *= 2;                         // Multiply by 2
    cout << "a = " << a << endl;
    a -= 2;                         // Subtract 2
    cout << "a = " << a << endl;
    a /= 2;                         // Divide by 2
    cout << "a = " << a << endl;
    a %= 2;                         // Mod by 2
    cout << "a = " << a << endl;

    return 0;
}

Sample Run

a = 6
a = 5

a = 5
a = 7
a = 7
a = 5

b = 11

a = 6
a = 8
a = 16
a = 14
a = 7
a = 1



Return to Lectures page


e-mail me at robbk@hsc.edu

This page was last modified on Tue Dec 7 16:04:26 1999 .

URL: http://people.hsc.edu/faculty-staff/robbk/Coms261/Examples/Increment.html

Return to Coms 261 home page