How to solve increment and decrement operators
Increment and decrement operators
Q) Explain increment and decrement operators in C.
- C allows two really beneficial operators not generally found within other languages. These are increment(++) and decrement (--) operators. Both are unary operators.
![]() |
Image Source ~ Crafted With ©Ishwaranand - 2020 ~ Image by ©Ishwaranand |
Increment operator
- The increment operator (++) is used to increase the value of the variable by 1(one). It means: a=a+1; is similar to a++;
Following are the two types of increment operators:
- Pre-increment operator(++1)
The pre-increment operator (++1) is used to increment the value of the variable before it is getting used. It means this operator increment the value and that incremented value is then used.
Example:
void main()
{
int a = 10, b;
b = ++a;
printf("a = %d b = %d", a, b);
getch();
}
Output:
a = 11 b = 11
- Post increment operator (i++)
The post-increment operator (i++) is used to increment the value of the variable after it is used. It means this operator postpones the increment of the value.
Example:
void main()
{
int a = 10, b;
b= a++;
printf ("a = %d b = %d", a, b);
getch();
}
Output:
a=11 b=10
Decrement operator
The decrement operator --is used to decrease the value variable by 1(one). It means:
a=a-1; is similar to a--;
Following are the two types of decrement operators;
- Pre decrement operator(--i)
The pre decrement operator (--i) is use to decrement the value of variable before it is getting used. It means this operator decreases the value and that decreased value is then used.
void main()
{
int a=10,b;
b=--a * 2;
printf ("a=% d b =%d", a, b);
getch();
}
Output:
a=9 b=18
- The post-increment operator(i--)
The post decrement operator (i--) is used to decrease the value of the variable after it is used. It means this operator postpones the decrement of the value.
Example:
void main()
{
int a=10, b;
b=a-- * 2;
printf ("a=%d b=%d", a, b);
getch ();
}
output:
a=9 b=20