Tuesday, 9 May 2017

Operator


Operators in C Language

C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler to perform certain mathematical or logical manipulations. Operators are used in program to manipulate data and variables.

1-Arithmetic operators

C supports all the basic arithmetic operators. The following table shows all the basic arithmetic operators.
Operator Description
+
adds two operands
-
subtract second operands from first
*
multiply two operand
/
divide numerator by denumerator
%
remainder of division
++
Increment operator increases integer value by one
--
Decrement operator decreases integer value by one

Note: ‘%’ cannot be used on floating data type.

Live Example : C Program to Verify Arithmetic Operator and Operation

#include <stdio.h>    
int main()  
{      
int num1,num2;      
int sum,sub,mult,div,mod;        
printf("\nEnter First Number :");      
scanf("%d",&num1);      
printf("\nEnter Second Number :");      
scanf("%d",&num2);        
sum = num1 + num2;      
printf("\nAddition is : %d",sum);        
sub = num1 - num2;      
printf("\nSubtraction is : %d",sub);        
mult = num1 * num2;      
printf("\nMultiplication is : %d",mult);        
div = num1 / num2;      
printf("\nDivision is : %d",div);        
mod = num1 % num2;      
printf("\nModulus is : %d",mod);        
return(0);  
}

Output :

Enter First Number : 10  
Enter Second Number : 5    
Addition is : 15  
Subtraction is : 5  
Multiplication is : 50  
Division is : 2  
Modulus is : 0

Increment Operator in C Programming

  1. Increment operator is used to increment the current value of variable by adding integer 1.
  2. Increment operator can be applied to only variables.
  3. Increment operator is denoted by ++.

Different Types of Increment Operation

In C Programming we have two types of increment operator i.e Pre-Increment and Post-Increment Operator.

A. Pre Increment Operator

Pre-increment operator is used to increment the value of variable before using in the expression. In the Pre-Increment value is first incremented and then used inside the expression.
b = ++y;  
In this example suppose the value of variable ‘y’ is 5 then value of variable ‘b’ will be 6 because the value of ‘y’ gets modified before using it in a expression.

B. Post Increment Operator

Post-increment operator is used to increment the value of variable as soon as after executing expression completely in which post increment is used. In the Post-Increment value is first used in a expression and then incremented.
b =   x++;  
In this example suppose the value of variable ‘x’ is 5 then value of variable ‘b’ will be 5 because old value of ‘x’ is used.

Sample program

#include<stdio.h>    
void main()  
{  
int a,b,x=10,y=10;    
a = x++;  
b = ++y;    
printf("Value of a : %d",a);  
printf("Value of b : %d",b);  
}  
Output :
Value of a : 10  Value of b : 11

Tip #1 : Increment Operator should not be used on Constants

We cannot use increment operator on the constant values because increment operator operates on only variables. It increments the value of the variable by 1 and stores the incremented value back to the variable,
b = ++5;  
Or
b = 5++;  

Decrement Operator in C Programming :

  1. Decrement operator is used to decrease the current value of variable by subtracting integer 1.
  2. Like Increment operator, decrement operator can be applied to only variables.
  3. Decrement operator is denoted by –.

Different Types of Decrement Operation :

When decrement operator used in C Programming then it can be used as pre-decrement or post-decrement operator.

A. Pre Decrement Operator

Pre-decrement operator is used to decrement the value of variable before using in the expression. In the Pre-decrement value is first decremented and then used inside the expression.
b = --var;
Suppose the value of variable var is 10 then we can say that value of variable ‘var’ is firstly decremented then updated value will be used in the expression.

B. Post Decrement Operator

Post-decrement operator is used to decrement the value of variable immediatly after executing expression completely in which post decrement is used. In the Post-decrement old value is first used in a expression and then old value will be decrement by 1.
b = var--;
Value of variable ‘var’ is 5. Same value will be used in expression and after execution of expression new value will be 4.

C Program

#include<stdio.h>    
void main() 
{  
int a,b,x=10,y=10;    
a = x--;  
b = --y;    
printf("Value of a : %d",a);  
printf("Value of b : %d",b);    
}  
Output :
Value of a : 10  Value of b : 9

Tip #1 : Decrement Operator should not be used on Constants

We cannot use decrement operator in the following case –
b = --5;
Or
b = 5--;

Precedence Power : Which Operator have Highest Priority ?

If we consider all the arithmetic operators then we can say that Multiplication and division operator have highest priority than addition and subtraction operator. Following table clearly explains the priority of all arithmetic operators in C programming –

Priority Rank Operator Description Operator Associativity
1 Multiplication
*
Left to Right
1 Division
/
Left to Right
1 Modulo
%
Left to Right
2 Addition
+
Left to Right
2 Subtraction
-
Left to Right


2-Relation operators

The following table shows all relation operators supported by C.
Operator Description
==
Check if two operand are equal
!=
Check if two operand are not equal.
>
Check if operand on the left is greater than operand on the right
<
Check operand on the left is smaller than right operand
>=
check left operand is greater than or equal to right operand
<=
Check if operand on left is smaller than or equal to right operand

3-Logical operators

C language supports following 3 logical operators. Suppose a=1 and b=0,
Operator Description Example
&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false

Logical Operator Chart :

Operator Applied Between Condition 1 Condition 2 Final Output
AND
True True True
True False False
False True False
False False False
OR
True True True
True False True
False True True
False False False
NOT
True - False
False - True
Let us look at all logical operators with example –
#include<stdio.h>  
int main()  
{      
int num1 = 30;      
int num2 = 40;            
if(num1>=40 || num2>=40)          
printf("Or If Block Gets Executed");        
if(num1>=20 && num2>=20)          
printf("And If Block Gets Executed");        
if( !(num1>=40))          
printf("Not If Block Gets Executed");            
return(0);  
}  

Output :

Or If Block Gets Executed  And If Block Gets Executed  Not If Block Gets Executed  


4-Bitwise operators

Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of bits from right to left. Bitwise operators are not applied to float or double.
Operator Description
&
Bitwise AND
|
Bitwise OR
^
Bitwise exclusive OR
<<
left shift
>>
right shift
Now lets see truth table for bitwise &, | and ^
a b a & b a | b a ^ b
0
0
0
0
0
0
1
0
1
1
1
0
0
1
1
1
1
1
1
0
The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the same precedence.
Example :
a = 0001000  b= 2  a << b = 0100000   a >> b = 0000010   


Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y=  01010000
All bit wise operations for x and y are given below.
  1. x&y = 00000000 (binary) = 0 (decimal)
  2. x|y = 01111000 (binary) = 120 (decimal)
  3. ~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -41 (decimal)
  4. x^y = 01111000 (binary) = 120 (decimal)
  5. x << 1 = 01010000 (binary) = 80 (decimal)
  6. x >> 1 = 00010100 (binary) = 20 (decimal)
Note:
  • Bit wise NOT : Value of 40 in binary is 00000000000000000000000000000000 00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit wise NOT operation.
  • Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be left shifted by one place. If we use it as “x << 2 “,  then, it means that the bits will be left shifted by 2 places.

Example program for bit wise operators in C:

In this example program, bit wise operations are performed as shown above and output is displayed in decimal format.
#include <stdio.h>
int main()
{
   int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
   AND_opr = (m&n);
   OR_opr = (m|n);
   NOT_opr = (~m);
   XOR_opr = (m^n);
   printf("AND_opr value = %d\n",AND_opr );
   printf("OR_opr value = %d\n",OR_opr );
   printf("NOT_opr value = %d\n",NOT_opr );
   printf("XOR_opr value = %d\n",XOR_opr );
   printf("left_shift value = %d\n", m << 1);
   printf("right_shift value = %d\n", m >> 1);

Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20


5-Assignment Operators

Assignment operators supported by C language are as follows.
Operator Description Example
=
assigns values from right side operands to left side operand a=b
Short hand assignment operator
+=
adds right operand to the left operand and assign the result to left a+=b is same as a=a+b
-=
subtracts right operand from the left operand and assign the result to left operand a-=b is same as a=a-b
*=
mutiply left operand with the right operand and assign the result to left operand a*=b is same as a=a*b
/=
divides left operand with the right operand and assign the result to left operand a/=b is same as a=a/b
%=
calculate modulus using two operands and assign the result to left operand a%=b is same as a=a%b

6-Conditional operator

It is also known as ternary operator and used to evaluate conditional expression.
epr1 ? expr2 : expr3  
If epr1 Condition is true ? Then value expr2 : Otherwise value expr3

7-Special operator

Operator Description Example
sizeof
Returns the size of an variable sizeof(x) return size of the variable x
&
Returns the address of an variable &x ; return address of the variable x
*
Pointer to a variable *x ; will be pointer to a variable x

8-Comma Operator

#include<stdio.h>  
void main() 
{     
int num1 = 1, num2 = 2;     
int res;     
res = (num1, num2);     
printf("%d", res);  
}  
Explanation :
  1. Comma Operator has Lowest Precedence i.e it is having lowest priority so it is evaluated at last.
  2. Comma operator returns the value of the rightmost operand when multiple comma operators are used inside an expression.
  3. Comma Operator Can acts as –
    • Operator  : In the Expression
    • Separator : Declaring Variable , In Function Call Parameter List

Usage of Comma Operator

Consider above example –

Comma as Separator

int num1 = 1, num2 = 2;  
It can acts as Seperator in –
  1. Function calls
  2. Function definitions
  3. Variable declarations
  4. Enum declarations

Comma as Operator

res = (num1, num2);  
In this case value of rightmost operator will be assigned to the variable. In this case value of num2 will be assigned to variable res.

9-Arrow operator (->)

Arrow operator is used for accessing members of structure using pointer variable, below is the syntax of arrow operator in c programming –

Syntax of arrow operator

struct student  
{    
char name[20],    int roll;  
}*ptr;  

Expalanation :

Whenever we declare structure variable then member can be accessed using the dot operator. But when pointer to a structure is used then arrow operator is used.
Both dot and arrow operator serves same function to access member of structure. Lets compare dot operator and arrow operator –
struct student  
{    
char name[20],    
int roll;  
}std;  
struct student  
{    
char name[20],    
int roll;  
}*ptr;  
Access Structure Member Example 1 Example 2
Name is accessed using std.name ptr->name
Roll number is accessed using std.roll ptr->roll
We can conclude that arrow operator is used to access the structure members when we use pointer variable to access it
In case if we want to access the members of structure using ordinary structure variable then we can use dot operator.
You can find nice explanation about the existence of arrow operator in c programming.

Arrow operator : Program

#include<stdio.h>  
#include<malloc.h>    
struct emp 
{     
int eid;     
char name[10];  
}*ptr;    
int main() 
{     
int i;       
printf("Enter the Employee Details : ");     
ptr = (struct emp *) malloc(sizeof(struct emp));       
printf("\nEnter the Employee ID : ");     
scanf("%d", &ptr->eid);     
printf("\nEnter the Employee Name : ");     
scanf("%s", ptr->name);       
printf("\nEmployee Details are : ");     
printf("\nRoll Number : %d", ptr->eid);     
printf("\nEmployee Name : %s", ptr->name);       
return (0);  
}  
Output :
Enter the Employee Details :  
Enter the Employee ID : 1  
Enter the Employee Name : Pritesh    
Employee Details are :  
Employee ID  : 1  
Name         : Pritesh  

10- sizeof operator

  1. sizeof operator is used to calcualte the size of data type or variables.
  2. sizeof operator can be nested.
  3. sizeof operator will return the size in integer format.
  4. sizeof operator syntax looks more like a function but it is considered as an operator in c programming

Example of sizeof() operator

Size of Variables

#include<stdio.h>    
int main() 
{       
int ivar = 100;     
char cvar = 'a';     
float fvar = 10.10;       
printf("%d", sizeof(ivar));     
printf("%d", sizeof(cvar));     
printf("%d", sizeof(fvar));     
return 0;  
}  
Output :
214
In the above example we have passed a variable to sizeof operator. It will print the value of variable using sizeof() operator.

Size of Data Type

#include<stdio.h>    
int main() 
{       
printf("%d", sizeof(int));     
printf("%d", sizeof(char));     
printf("%d", sizeof(float));          
return 0;  
}  
We will again get same output as that of above program. In this case we have directly passed an data type to an sizeof.

Size of constant

#include<stdio.h>    
int main() 
{       
printf("%d", sizeof(10));     
printf("%d", sizeof('A'));     
printf("%d", sizeof(10.10));          
return 0;  
}  
In this example we have passed the constant value to a sizeof operator. In this case sizeof will print the size required by variable used to store the passed value.

Nested sizeof operator

#include<stdio.h>    
int main() 
{     
int num = 10;     
printf("%d", sizeof(num));     
return 0;  
}  
We can use nested sizeof in c programming. Inner sizeof will be executed in normal fashion and the result of inner sizeof will be passed as input to outer sizeof operator.
Innermost Sizeof operator will evaluate size of Variable “num” i.e 2 bytes Outer Sizeof will evaluate Size of constant “2” .i.e 2 bytes

No comments:

Post a Comment

Please write your view and suggestion....