Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a C program to demonstrate post increment and pre increment operators
In C programming, the increment (++) and decrement (--) operators are used to increase or decrease a variable's value by 1. These operators can be applied in two forms: pre-increment/decrement and post-increment/decrement, which behave differently in expressions.
Syntax
/* Pre-increment/decrement */ ++variable; --variable; /* Post-increment/decrement */ variable++; variable--;
Pre-Increment Operator (++variable)
In pre-increment, the operator is placed before the operand. The value is first incremented and then the operation is performed on it.
For example −
z = ++a; // First: a = a + 1, Then: z = a
Example
Following is an example for pre-increment operator −
#include <stdio.h>
int main() {
int a = 10, z;
z = ++a;
printf("z = %d<br>", z);
printf("a = %d<br>", a);
return 0;
}
z = 11 a = 11
Post-Increment Operator (variable++)
In post-increment, the operator is placed after the operand. The value is incremented after the operation is performed.
For example −
z = a++; // First: z = a, Then: a = a + 1
Example
Following is an example for post-increment operator −
#include <stdio.h>
int main() {
int a = 10, z;
z = a++;
printf("z = %d<br>", z);
printf("a = %d<br>", a);
return 0;
}
z = 10 a = 11
Pre-Decrement Operator (--variable)
The decrement operator works similarly to increment but reduces the value by 1. In pre-decrement, the value is first decremented and then used in the expression.
Example
Following is an example for pre-decrement operator −
#include <stdio.h>
int main() {
int a = 10, z;
z = --a;
printf("z = %d<br>", z);
printf("a = %d<br>", a);
return 0;
}
z = 9 a = 9
Post-Decrement Operator (variable--)
In post-decrement, the current value is used in the expression first, then the variable is decremented.
Example
Following is an example for post-decrement operator −
#include <stdio.h>
int main() {
int a = 10, z;
z = a--;
printf("z = %d<br>", z);
printf("a = %d<br>", a);
return 0;
}
z = 10 a = 9
Key Points
- Pre-operators modify the variable before using it in the expression.
- Post-operators use the current value in the expression, then modify the variable.
- Both forms change the variable's value, but the timing affects the result of expressions.
Conclusion
Understanding the difference between pre and post increment/decrement operators is crucial for writing correct C programs. The choice between them depends on whether you need the original or modified value in your expression.
