Increment & Decrement Operators in C - C-Tutorial

Latest

Wednesday, 16 November 2016

Increment & Decrement Operators in C

Increment & Decrement Operators

++ and – operators are called increment and decrement operators.  These operators are unary operators because it requires only one operand.


Increment Operator: Increment operator ++ is used to increment the operand value by 1.  Depending on the placement of operator with the operand, increment operator can be utilized in two ways as : pre-increment and post-increment.

If ++ operator is placed before the operand, it is termed as pre-increment operation.  Here, first compiler increments the operand value by 1 and then result is assigned to the variable.

If ++ operator is placed after the operand, it is termed as post-increment operation.  Here, first compiler assigns the value to the variable and then operand is incremented by 1.

/* EXAMPLE PROGRAM FOR INCREMENT OPERATORS */

#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
x=10;
y=++x;
printf("\nPre-Increment X Value:%d",x);
printf("\nPre-Increment Y Value:%d",y);
x=45;
y=x++;
printf("\nPost-Increment X Value:%d",x);
printf("\nPost-Increment Y Value:%d",y);
}

Decrement Operator: Decrement operator -- is used to decrement the operand value by 1.  Depending on the placement of operator with the operand, decrement operator can be utilized in two ways as : pre-decrement and post-decrement.

If -- operator is placed before the operand, it is termed as pre-decrement operation.  Here, first compiler decrements the operand value by 1 and then result is assigned to the variable.

If -- operator is placed after the operand, it is termed as post-decrement operation.  Here, first compiler assigns the value to the variable and then operand value is decremented by 1.

/* EXAMPLE PROGRAM FOR DECREMENT OPERATORS */

#include<stdio.h>
#include<conio.h>
main()
{
int x,y;
clrscr();
x=10;
y=--x;
printf("\nPre-Decrement X Value:%d",x);
printf("\nPre-Decrement Y Value:%d",y);
x=45;
y=x--;
printf("\nPost-Decrement X Value:%d",x);
printf("\nPost-Decrement Y Value:%d",y);
}

Note: Increment and Decrement operators can’t be applied on constant values.

No comments:

Post a Comment