This C++ program demonstrates the difference between prefix and postfix increment and decrement operators. It declares an integer variable num, initializes it to 9, and uses num++ and ++num in different statements. It outputs the value of num after each operation and the values stored in another variable store. The program illustrates that prefix and postfix operators can produce different results depending on when the increment/decrement occurs.
1. 1 /*********************************************************
2 /* Sample program for increment and decrement operators *
3 /* Illustrating the difference between prefix and postfix operations *
4 /* Also illustrates the use of escape squence t for creating columns *
5 /* TSPaccarangan *
6 /* September 13, 2009 *
7 /********************************************************/
8 #include <iostream>
9 using namespace std;
10
11 int main()
12 {
13 int num=9;
14 int store(0);
15 cout << "Let num be equal to 9: num = 9.n";
16 num++;
17 cout << "Using the expression num++ the value of that number is now: " << num << ".n";
18 num--;
19 cout << "nNow, using the expression num-- the value of the number is back to: “
20 cout << num << ".n";
21 cout << "nLet's play some more :)n";
22 cout << "nLet us now assign the output of num++ and ++num in another variable store.n";
23 store = 10*num++;
24 cout << "nWith the statement store = 10 * num++, n" << " new num is " << num << endl;
25 cout << " and store is " << store << endl;
26 num--;
27 store = 10*++num;
28 cout << "nWith the statement store = 10 * ++num,n" << " new num is " << num << endl;
29 cout << " and store is " << store << endl;
30
31 cout << "nnLet's use a table to display the previous discussion. nn";
32
33 cout << "t|statementtt|old numt|num used in *t|storet|new numn";
34 cout << "t|store = 10*num++t|9tt|9tt|90t|10n";
35 cout << "t|store = 10*++numt|9tt|10tt|100t|10n";
36 cout << "nnum is increased by 1 in both instances.n";
37 cout << "But the values multiplied by the constant are different.n";
38
39 return 0;
40 }
F o r u s e i n c o n j u n c t i o n w i t h l e s s o n o n I n c r e m e n t a n d D e c r e m e n t O p e r a t o r s Se p t e m b e r 1 4 , 2 0 0 9