Increment and Decrement Operators
C language permits two very useful operators not commonly found in other languages. Those are increment and decrement operators, ++ and --. The operation ++ adds 1 to its single operand and -- subtracts 1. Thus, the following are equivalent operations: -
x = x+1;
is the same as
x++; or ++x;
and
x = x - 1;
is the same as
x--; or --x;
The increment and decrement operators might either precede or follow the operand. Thus, there is a difference whenever they are used in expressions. Whenever an increment or decrement operator precedes its operand, C++ language performs the increment or decrement operation prior to by using the operand's value. C uses the value of the operand's value after incrementing or decrementing it if the operator follows its operand.
Let consider the following example:
x = 10;
y = ++x;
In the given case, y is set to 11.
Therefore, if the code had been written as x = 10;
y = x++;
y would have been set to 10. With both the cases, x is set to 11; the difference is, whenever it occurs.
Let's see how different types of arithmetic operators can be used in a program:-
# include <iostream.h>
main()
{
int a, b, c, d, x, y, p, q;
a=20; b=35; c= a+b; d= b-a;
cout<<"******Addition AND Subraction*****";
cout<<"a = "<<"b =\n"<< a<< b;
cout<<" c = "<<"d = \n"<<c<<d;
x = b / a;
y = b % a;
cout<<"******Division AND Modulus******";
cout<<"x =\n"<<x;
cout<<"y = \n"<<y);
p=++a;
q= c + b--;
cout<<"******Increment AND Decrement******";
cout<<"a = \n"<<a);
cout<<"b =\n"<<b);
cout<<"p = \n"<<p);
cout<<"q = \n"<<q);
}
The output is:
Addition AND Subraction a=20 b = 35 c= 55 d = 15
Division AND Modulus x= 1 y= 15
Increment AND Decrement a= 21 b= 34 p= 36 q= 71