Sunday, May 27, 2018

Increment and Decrement Operator in C++

Increment operators  ஒரு மாறி மதிப்பை அதிகரிக்க பயன்படுகிறது  மற்றும் Decrement Operator ஒரு மாறி மதிப்பு  குறைக்க பயன்படுத்தப்படுகின்றன.

Syntax
            ++  // increment operator
            --   // decrement operator

Type of Increment Operator

pre-increment
post-increment

pre-increment (++ variable)
In pre-increment first increment the value of variable and then used inside the expression (initialize into another variable).

Syntax
++ variable;

Example pre-increment in C++

#include<iostream>

void main()
{
int x,i;
i=10;
x=++i;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}

Output
x: 11
i: 11

In above program first increase the value of i and then used value of i into expression.

post-increment (variable ++)

In post-increment first value of variable is use in the expression (initialize into another variable) and then increment the value of variable.

Syntax
variable ++;

Example post-increment

#include<iostream>

void main()
{
int x,i;
i=10;
x=i++;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}

Output
x: 10
i: 11

In above program first used the value of i into expression then increase value of i by 1.

Type of Decrement Operator

pre-decrement
post-decrement
Pre-decrement (-- variable)

In pre-decrement first decrement the value of variable and then used inside the expression (initialize into another variable).

Syntax
-- variable;

Example pre-decrement

#include<iostream>

void main()
{
int x,i;
i=10;
x=--i;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}

Output
x: 9
i: 9

In above program first decrease the value of i and then value of i used in expression.

post-decrement (variable --)

In Post-decrement first value of variable is use in the expression (initialize into another variable) and then decrement the value of variable.

Syntax
variable --;

Example post-decrement

#include<iostream>

void main()
{
int x,i;
i=10;
x=i--;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}

Output
x: 10
i: 9

In above program first used the value of x in expression then decrease value of i by 1.

Example of increment and decrement operator


Example
#include<iostream>

void main()
{
int x,a,b,c;
a = 2;
b = 4;
c = 5;
x = a-- + b++ - ++c;
cout<<"x: "<<x;
getch();
}

Output
x: 0

No comments:

Post a Comment