The Pre and Post increment operators in C++ are a very useful tool to avoid adding 1 to variables.
Pre increment => ++x i.e the value of x will be incremented before x is computed with any other variable.
Post increment => x++ i.e the value of x will be incremented after x is computed with any other variable.
I've written a program to demonstrate the above concept by taking the same input from the user and performing pre and post increment operations to show the difference between the two operators.
The pre decrement and post decrement operators work in the same manner.
// Program to demonstrate Pre and Post increment operators
#include<iostream.h>
using namespace std;
int main()
{
int x,y,result;
cout<<" Enter the value of x : "; // takes input from the user
cin>>x;
// Pre Increment
y = 7;
result = y + (++x);
cout<<" \n Value of result after pre increment : "<<result;
// Post Increment
cout<<" \n\n Now enter the SAME value of x again : ";
cin>>x;
// Same operation is performed again with the same value of x
result = y + (x++);
cout<<" \n Value of result after post increment : "<<result;
return 0;
} // end of main
Pre increment => ++x i.e the value of x will be incremented before x is computed with any other variable.
Post increment => x++ i.e the value of x will be incremented after x is computed with any other variable.
I've written a program to demonstrate the above concept by taking the same input from the user and performing pre and post increment operations to show the difference between the two operators.
The pre decrement and post decrement operators work in the same manner.
// Program to demonstrate Pre and Post increment operators
#include<iostream.h>
using namespace std;
int main()
{
int x,y,result;
cout<<" Enter the value of x : "; // takes input from the user
cin>>x;
// Pre Increment
y = 7;
result = y + (++x);
cout<<" \n Value of result after pre increment : "<<result;
// Post Increment
cout<<" \n\n Now enter the SAME value of x again : ";
cin>>x;
// Same operation is performed again with the same value of x
result = y + (x++);
cout<<" \n Value of result after post increment : "<<result;
return 0;
} // end of main
0 comments:
Post a Comment
Comment Here....