Increment and decrement operators

Default Image

nary operators that are used to add or
subtract 1 from a variable called unary operator. It is used to make
some ease in programming. Such as to add 1 in a variable you must write
as:

  • a=a+1;

but with the use of increment operator you can write this as:


  • a++;


Both above statements can be used to make
an increase of 1 in variable a’s value. So, it is more handy practice
to use increment operator instead of arithmetic plus. There are two
types to use these increment and decrement operators:


  • prefix
  • postfix

Prefix increment and decrement


In prefix we write an expression such as:


  • ++a;

In above expression increment operator is in start and then our variable. What will be its effect lets try a simple programme:


#include


#include


void main()


{


int a=5;


cout << a << endl;


cout << ++a << endl;


cout << a << endl;


getch();


}


In above programme you can observe that
the initial value of a is 5, when we apply prefix on variable it
immediately makes increase of 1 in the previous value of a and print it
out on computer screen. On third line the value of a is same as previous
line. Decrement also works in same method. In prefix first, the value
is increased or decreased and then any other task (e.g. print, assigning
value of variable to any other variable  etc.) is performed.


Postfix increment and decrement


In postfix we write an expression such as:


  • a++;

In above expression increment operator is in the end of our variable. What will be its effect lets try a simple programme:


#include


#include


void main()


{


int a;


a = 5;


cout << a << endl;


cout << a++ << endl;


cout << a << endl;


getch();


}


In above programme you can observe that
the initial value of a is 5, when we apply postfix on variable it did
not makes increase of 1 in the previous value of a and print it out on
computer screen. On third line the value of a is increased. Decrement
also works in same method. In postfix first, the task (e.g. print,
assigning value of variable to any other variable etc.) is performed and
then value is increased or decreased.

Read Count: 3 times

Comments

No comments yet.

Leave a Comment