Increment and Decrement Operator
These operators are used to either increase or decrease the value of the variable by one.
The increment operator (++) and decrement operator (–) are both unary operators.
Increment Operator (++)
The operator ++ adds 1 (one) to the operand. Increment operator can be used in two forms.
(i). post increment (i++)
(ii). Pre increment (++i)
(i) Post increment operator (i++)
int i=1,n; | ||
n=i++; | n=i; i=i+1; |
n=1; i=2; |
In post increment the value of the variable is used first and then it is incremented.
#include<stdio.h> int main() { int a,i=10; a=i++; printf("a = %d i = %d\n",a,i); return(0); }
/* Output */ a = 10 i = 11
(ii)Pre increment Operator (++i)
int i=1,n; | ||
n=++i; | i=i+1; n=i; |
i=2; n=2; |
In pre increment the value of the variable is incremented first and then it is used.
Note: i++ or ++i when used independently mean the same that is increment the value by one.
if we have a=10;
a++;
++a;
a=a+1;
a+=1;
On execution of any of the above statements we will get
a=11;
#include<stdio.h> int main() { int a,i=10; a=++i; printf("a = %d i = %d\n",a,i); return(0); }
/* Output */ a = 11 i = 11