Increment and Decrement Operators in C++
In C++, Increment and Decrement operators are used to increase or decrease the value of a variable by 1.
The increment operator (++) increases the value of a variable by 1, while the decrement operator (--) decreases the value of a variable by 1. These operators are commonly used in loops, counters, and calculations.
Types of Increment and Decrement Operators
In C++, both increment and decrement operators are used in two ways:
- Pre-Increment / Pre-Decrement
- Post-Increment / Post-Decrement
1. Pre-Increment Operator (++a)
In Pre-Increment, the value of the variable is increased first, and then it is used in the expression.
// Example of Pre-Increment
#include <iostream>
using namespace std;
int main() {
int a = 5;
cout << "Value of a : " << a << endl;
cout << "After ++a : " << ++a << endl;
return 0;
}
Output:
Value of a : 5
After ++a : 6
Explanation
- Initially, a = 5.
- ++a increases the value first.
- So the value becomes 6 before printing.
2. Post-Increment Operator (a++)
In Post-Increment, the value of the variable is used first and then it is increased.
// Example of Post-Increment
#include <iostream>
using namespace std;
int main() {
int a = 5;
cout << "Value of a : " << a << endl;
cout << "Using a++ : " << a++ << endl;
cout << "Value of a after increment : " << a << endl;
return 0;
}
Output
Value of a : 5
Using a++ : 5
Value of a after increment : 6
Explanation
- Initially, a = 5.
- a++ first prints the current value.
- After printing, the value increases to 6.
Decrement Operator (--)
The decrement operator (--) reduces the value of a variable by 1. It also works in two forms: pre-decrement (--a) and post-decrement (a--).
// Example of Decrement Operator
#include <iostream>
using namespace std;
int main() {
int a = 8;
cout << "Value of a : " << a << endl;
cout << "After --a : " << --a << endl;
cout << "Using a-- : " << a-- << endl;
cout << "Final value of a : " << a << endl;
return 0;
}
Output
Value of a : 8
After --a : 7
Using a-- : 7
Final value of a : 6
Summary:
- Increment (++) increases the value of a variable by 1.
- Decrement (--) decreases the value of a variable by 1.
- Pre-Increment (++a) increases the value first, then uses it.
- Post-Increment (a++) uses the value first, then increases it.
- These operators are commonly used in loops and counters.