Increment or Decrement in C++
About Increment or Decrement :
In C++, Increment operator ++ will increase the value by 1 in the program while decrement operator — will decrease the value by 1 in the program.Types of Increment or Decrement Operator in C++
In general, There are two types of operator : prefix operator and postfix operator.
- Prefix Operator
- Postfix Operator
Prefix Definition
In Prefix Incrementation ++val or Prefix decrementation --val, value will first increase by 1 or decrease by 1 then it will return.
Postfix Definition
In Postfix Incrementation val++ or Postfix decrementation val--, first it will return the value and then value will increase by 1 or decrease by 1.
Example of Postfix Incrementation or Decrementation :
Run
#include<iostream> using namespace std; int main() { int val = 20; cout<<"value before postfix incrementation: "< < val++<< endl; cout<< "value after postfix incrementation: "< < val< < endl; cout<<"value before postfix decrementation: "< < val--< < endl; cout<< "value after postfix decrementation: "< < val< < endl; return 0; }
Output :
value before postfix incrementation: 20 value after postfix incrementation: 21 value before postfix decrementation: 21 value after postfix decrementation: 20
In the above program, we take the variable val 20 , val++ will print 20 and increase the value to 21, val– will print 21 and decrease the value to 20.
Example of Prefix Incrementation or Decrementation:
Run
#include<iostream> using namespace std; int main() { int val = 20; cout<<"value before prefix incrementation: "<<++val< < endl; cout<< "value after prefix incrementation: "<< val<< endl; cout<<"value before prefix decrementation: "<<--val<< endl; cout<< "value after prefix decrementation: "<< val<< endl; return 0; }
Output :
value before prefix incrementation: 21 value after prefix incrementation: 21 value before prefix decrementation: 20 value after prefix decrementation: 20
In the above program, we take the variable val 20 ,++ val will increase the value to 21 and print it while — val will decrease the value to 20 and print it.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment