Apply Increment/Decrement Operations
In this step, you'll learn how to use increment (++) and decrement (--) operators in C programming, exploring both pre-increment and post-increment techniques.
Open the previous file to modify the code:
cd ~/project
nano increment_demo.c
Update the code with increment and decrement operations:
#include <stdio.h>
int main() {
// Declare and initialize an integer variable
int counter = 10;
// Print the initial value
printf("Initial value: %d\n", counter);
// Post-increment operation
printf("Post-increment: %d\n", counter++);
printf("Value after post-increment: %d\n", counter);
// Pre-increment operation
printf("Pre-increment: %d\n", ++counter);
printf("Value after pre-increment: %d\n", counter);
// Decrement operations
printf("Post-decrement: %d\n", counter--);
printf("Value after post-decrement: %d\n", counter);
printf("Pre-decrement: %d\n", --counter);
printf("Value after pre-decrement: %d\n", counter);
return 0;
}
Compile and run the program:
gcc increment_demo.c -o increment_demo
./increment_demo
Example output:
Initial value: 10
Post-increment: 10
Value after post-increment: 11
Pre-increment: 12
Value after pre-increment: 12
Post-decrement: 12
Value after post-decrement: 11
Pre-decrement: 10
Value after pre-decrement: 10
Key differences between operators:
counter++
(post-increment): Returns the current value, then increments
++counter
(pre-increment): Increments first, then returns the new value
- Same logic applies to decrement (
--
) operators